实现vue组件
创建 Vue 组件
Vue 组件可以通过单文件组件(.vue 文件)或直接在 JavaScript 中定义。以下是两种常见实现方式。
单文件组件方式
单文件组件包含模板、脚本和样式三部分,适合复杂项目。示例代码如下:
<template>
<div class="example">
<h1>{{ title }}</h1>
<button @click="handleClick">点击</button>
</div>
</template>
<script>
export default {
data() {
return {
title: '示例组件'
}
},
methods: {
handleClick() {
alert('按钮被点击');
}
}
}
</script>
<style scoped>
.example {
color: #42b983;
}
</style>
JavaScript 对象方式
适用于简单场景或动态注册组件。示例代码如下:
const ExampleComponent = {
template: `
<div>
<h2>{{ message }}</h2>
</div>
`,
data() {
return {
message: '动态组件示例'
}
}
};
// 全局注册
Vue.component('example', ExampleComponent);
// 局部注册
new Vue({
components: { ExampleComponent }
});
组件通信方法
Props 传递数据
父组件通过属性向子组件传递数据:

<!-- 父组件 -->
<ChildComponent :value="parentData" />
<!-- 子组件 -->
<script>
export default {
props: ['value']
}
</script>
自定义事件通信
子组件通过 $emit 触发事件:
// 子组件
this.$emit('update', newValue);
// 父组件
<ChildComponent @update="handleUpdate" />
使用 Vuex 状态管理
适合跨层级组件共享状态:
// 组件中访问
this.$store.state.count;
// 修改状态
this.$store.commit('increment');
生命周期钩子使用
常用生命周期钩子示例:

export default {
created() {
console.log('组件实例已创建');
},
mounted() {
console.log('DOM 挂载完成');
},
beforeDestroy() {
console.log('组件销毁前');
}
}
动态组件实现
通过 <component> 标签实现动态切换:
<template>
<component :is="currentComponent"></component>
</template>
<script>
export default {
data() {
return {
currentComponent: 'ComponentA'
}
}
}
</script>
插槽使用
默认插槽
父组件传递内容到子组件指定位置:
<!-- 子组件 -->
<div>
<slot></slot>
</div>
<!-- 父组件 -->
<ChildComponent>插入的内容</ChildComponent>
具名插槽
实现多内容区域分发:
<!-- 子组件 -->
<div>
<slot name="header"></slot>
<slot></slot>
</div>
<!-- 父组件 -->
<ChildComponent>
<template v-slot:header>
<h1>标题</h1>
</template>
默认内容
</ChildComponent>






