vue中组件的实现
Vue 组件的基本实现
在 Vue 中,组件是可复用的 Vue 实例,通常包含模板、逻辑和样式。组件可以通过单文件组件(.vue 文件)或全局/局部注册的方式实现。
单文件组件示例:
<template>
<div>
<h1>{{ title }}</h1>
<button @click="handleClick">点击</button>
</div>
</template>
<script>
export default {
data() {
return {
title: 'Vue 组件示例'
}
},
methods: {
handleClick() {
alert('按钮被点击');
}
}
}
</script>
<style scoped>
h1 {
color: #42b983;
}
</style>
全局注册组件
通过 Vue.component 方法全局注册组件,可以在任何地方使用:
Vue.component('my-component', {
template: '<div>全局组件</div>'
});
局部注册组件
在父组件中通过 components 选项局部注册组件:
import ChildComponent from './ChildComponent.vue';
export default {
components: {
'child-component': ChildComponent
}
}
组件通信
Props 传递数据:
父组件通过 props 向子组件传递数据:
<template>
<child-component :message="parentMessage"></child-component>
</template>
<script>
export default {
data() {
return {
parentMessage: '来自父组件的数据'
}
}
}
</script>
子组件通过 props 接收数据:

export default {
props: ['message']
}
自定义事件通信:
子组件通过 $emit 触发事件:
this.$emit('update', newValue);
父组件监听事件:
<child-component @update="handleUpdate"></child-component>
插槽(Slots)
插槽用于在组件中插入动态内容:
<template>
<div>
<slot></slot>
</div>
</template>
具名插槽:

<template>
<div>
<slot name="header"></slot>
<slot name="footer"></slot>
</div>
</template>
动态组件
通过 <component> 标签和 is 属性实现动态组件切换:
<template>
<component :is="currentComponent"></component>
</template>
<script>
export default {
data() {
return {
currentComponent: 'component-a'
}
}
}
</script>
生命周期钩子
组件生命周期钩子可以在不同阶段执行逻辑:
export default {
created() {
console.log('组件创建完成');
},
mounted() {
console.log('组件挂载到 DOM');
},
beforeDestroy() {
console.log('组件销毁前');
}
}
混入(Mixins)
混入用于复用组件逻辑:
const myMixin = {
methods: {
hello() {
console.log('混入方法');
}
}
}
export default {
mixins: [myMixin],
created() {
this.hello();
}
}
函数式组件
函数式组件无状态、无实例,适合简单渲染场景:
Vue.component('functional-component', {
functional: true,
render(createElement, context) {
return createElement('div', context.props.message);
},
props: ['message']
});






