vue组件的实现
Vue 组件的基本实现
Vue 组件是 Vue.js 的核心特性之一,允许将 UI 拆分为独立、可复用的模块。组件的实现主要包括定义、注册和使用三个部分。
定义组件
// 单文件组件 (SFC) 形式 - MyComponent.vue
<template>
<div>{{ message }}</div>
</template>
<script>
export default {
data() {
return {
message: 'Hello Vue!'
}
}
}
</script>
<style scoped>
div {
color: red;
}
</style>
全局注册
import MyComponent from './MyComponent.vue'
Vue.component('my-component', MyComponent)
局部注册
import MyComponent from './MyComponent.vue'
export default {
components: {
MyComponent
}
}
组件通信方式
Props 父传子
// 父组件
<child-component :title="parentTitle"></child-component>
// 子组件
export default {
props: ['title']
}
自定义事件 子传父
// 子组件
this.$emit('update', newValue)
// 父组件
<child-component @update="handleUpdate"></child-component>
Provide/Inject 跨层级
// 祖先组件
export default {
provide() {
return {
theme: this.themeData
}
}
}
// 后代组件
export default {
inject: ['theme']
}
生命周期钩子
export default {
beforeCreate() {},
created() {},
beforeMount() {},
mounted() {},
beforeUpdate() {},
updated() {},
beforeDestroy() {},
destroyed() {}
}
动态组件
<component :is="currentComponent"></component>
data() {
return {
currentComponent: 'ComponentA'
}
}
插槽使用
默认插槽
// 父组件
<child-component>
<p>默认插槽内容</p>
</child-component>
// 子组件
<slot></slot>
具名插槽
// 父组件
<child-component>
<template v-slot:header>
<h1>标题</h1>
</template>
</child-component>
// 子组件
<slot name="header"></slot>
作用域插槽
// 子组件
<slot :user="user"></slot>
// 父组件
<child-component>
<template v-slot:default="slotProps">
{{ slotProps.user.name }}
</template>
</child-component>
高级组件模式
混入 (Mixin)
const myMixin = {
created() {
this.hello()
},
methods: {
hello() {
console.log('hello from mixin!')
}
}
}
export default {
mixins: [myMixin]
}
自定义指令
Vue.directive('focus', {
inserted: function (el) {
el.focus()
}
})
// 使用
<input v-focus>
渲染函数

export default {
render(h) {
return h('div', this.$slots.default)
}
}
组件最佳实践
- 组件命名采用 PascalCase 或 kebab-case
- 单向数据流原则,避免直接修改 props
- 合理划分组件职责,保持单一功能
- 使用 prop 验证和默认值
- 为可复用组件提供清晰的文档和示例
以上实现方式涵盖了 Vue 组件开发的主要方面,可以根据具体需求选择适合的模式和方法。






