vue怎么把组件实现
Vue 组件实现方法
组件定义
在 Vue 中,组件是可复用的 Vue 实例。通过 Vue.component 或单文件组件(.vue 文件)定义。
全局组件注册:
Vue.component('my-component', {
template: '<div>A custom component!</div>'
})
局部组件注册:
const ComponentA = {
template: '<div>Component A</div>'
}
new Vue({
el: '#app',
components: { 'component-a': ComponentA }
})
单文件组件
创建 .vue 文件,包含模板、脚本和样式:
<template>
<div class="example">{{ msg }}</div>
</template>
<script>
export default {
data() {
return { msg: 'Hello world!' }
}
}
</script>
<style>
.example { color: red; }
</style>
组件通信
父组件通过 props 传递数据给子组件:
Vue.component('child', {
props: ['message'],
template: '<span>{{ message }}</span>'
})
// 使用
<child message="hello!"></child>
子组件通过事件向父组件通信:
// 子组件
this.$emit('notify', data)
// 父组件
<child @notify="handleNotify"></child>
动态组件
使用 <component> 元素配合 is 特性实现动态组件切换:
<component :is="currentComponent"></component>
插槽内容分发
通过 <slot> 元素实现内容分发:
<!-- 组件模板 -->
<div class="container">
<slot></slot>
</div>
<!-- 使用 -->
<my-component>
<p>插入的内容</p>
</my-component>
生命周期钩子
组件有创建、挂载、更新和销毁等生命周期阶段,可在不同阶段执行逻辑:
export default {
created() {
// 实例创建后调用
},
mounted() {
// DOM挂载后调用
}
}
组件复用
通过 mixins 复用组件逻辑:
const myMixin = {
created() {
this.hello()
},
methods: {
hello() {
console.log('hello from mixin!')
}
}
}
// 使用
const Component = Vue.extend({
mixins: [myMixin]
})






