Vue组件实现方法
Vue 组件的基本实现
Vue 组件是 Vue.js 的核心概念之一,用于构建可复用的 UI 模块。组件可以封装 HTML、CSS 和 JavaScript,实现独立的功能单元。
全局注册组件
Vue.component('component-name', {
template: '<div>This is a global component</div>'
});
局部注册组件
const ComponentA = {
template: '<div>This is a local component</div>'
};
new Vue({
el: '#app',
components: {
'component-a': ComponentA
}
});
单文件组件 (SFC)
单文件组件是 Vue 推荐的组件组织形式,将模板、逻辑和样式封装在一个 .vue 文件中。
<template>
<div class="example">{{ msg }}</div>
</template>
<script>
export default {
data() {
return {
msg: 'Hello from single file component!'
}
}
}
</script>
<style>
.example {
color: red;
}
</style>
组件通信
Props 传递数据 父组件通过 props 向子组件传递数据:
<template>
<child-component :message="parentMsg"></child-component>
</template>
<script>
export default {
data() {
return {
parentMsg: 'Message from parent'
}
}
}
</script>
子组件接收 props:
export default {
props: ['message']
}
自定义事件通信
子组件通过 $emit 触发事件:
this.$emit('event-name', payload);
父组件监听事件:
<child-component @event-name="handleEvent"></child-component>
插槽 (Slots)
插槽允许组件接收模板片段,实现内容分发。
默认插槽
<!-- 组件定义 -->
<template>
<div>
<slot>Fallback content</slot>
</div>
</template>
<!-- 组件使用 -->
<my-component>
Content will replace the slot
</my-component>
具名插槽
<!-- 组件定义 -->
<template>
<div>
<slot name="header"></slot>
<slot></slot>
<slot name="footer"></slot>
</div>
</template>
<!-- 组件使用 -->
<my-component>
<template v-slot:header>
Header content
</template>
Main content
<template v-slot:footer>
Footer content
</template>
</my-component>
动态组件
使用 <component> 元素和 is 特性可以实现动态组件切换:
<template>
<component :is="currentComponent"></component>
</template>
<script>
export default {
data() {
return {
currentComponent: 'component-a'
}
}
}
</script>
生命周期钩子
Vue 组件提供了一系列生命周期钩子函数:
export default {
beforeCreate() {},
created() {},
beforeMount() {},
mounted() {},
beforeUpdate() {},
updated() {},
beforeDestroy() {},
destroyed() {}
}
混入 (Mixins)
混入是一种分发 Vue 组件可复用功能的灵活方式:

const myMixin = {
created() {
this.hello();
},
methods: {
hello() {
console.log('hello from mixin!');
}
}
};
export default {
mixins: [myMixin]
}






