vue组件怎么实现
vue组件实现方法
创建Vue组件是Vue.js开发中的核心概念之一,可以通过多种方式实现组件化开发。
单文件组件(SFC)
使用.vue文件组织组件模板、逻辑和样式:
<template>
<div class="example">{{ msg }}</div>
</template>
<script>
export default {
data() {
return {
msg: 'Hello world!'
}
}
}
</script>
<style>
.example {
color: red;
}
</style>
全局组件注册
通过Vue.component()方法全局注册组件:

Vue.component('my-component', {
template: '<div>A custom component!</div>'
})
局部组件注册
在父组件中局部注册子组件:
const ChildComponent = {
template: '<div>Child Component</div>'
}
new Vue({
components: {
'child-component': ChildComponent
}
})
组件通信方式
父子组件通过props和events通信:

// 父组件
<template>
<child-component :message="parentMsg" @update="handleUpdate"/>
</template>
// 子组件
Vue.component('child-component', {
props: ['message'],
methods: {
notifyParent() {
this.$emit('update', newValue)
}
}
})
动态组件
使用标签配合is属性实现动态组件:
<template>
<component :is="currentComponent"></component>
</template>
函数式组件
创建无状态、无实例的轻量组件:
Vue.component('functional-button', {
functional: true,
render(createElement, context) {
return createElement('button', context.data, context.children)
}
})
组件生命周期
组件具有创建、挂载、更新和销毁等生命周期钩子:
export default {
created() {
// 实例创建后
},
mounted() {
// DOM挂载后
},
beforeDestroy() {
// 实例销毁前
}
}






