vue如何实现组件化
Vue 组件化实现方法
创建组件
Vue 组件可以通过 .vue 单文件组件或全局/局部注册实现。单文件组件包含 <template>、<script> 和 <style> 三个部分,例如:
<template>
<div class="example">{{ message }}</div>
</template>
<script>
export default {
data() {
return { message: 'Hello Vue!' }
}
}
</script>
<style scoped>
.example { color: red; }
</style>
注册组件
全局注册使用 Vue.component,局部注册在父组件的 components 选项中声明:
// 全局注册
Vue.component('my-component', {
template: '<div>全局组件</div>'
});
// 局部注册
export default {
components: { 'my-component': MyComponent }
}
组件通信
-
Props 向下传递:父组件通过属性传递数据,子组件用
props接收:<!-- 父组件 --> <child-component :title="parentTitle"></child-component> <!-- 子组件 --> <script> export default { props: ['title'] } </script> -
事件向上传递:子组件通过
$emit触发事件,父组件监听:<!-- 子组件 --> <button @click="$emit('update', newValue)">提交</button> <!-- 父组件 --> <child-component @update="handleUpdate"></child-component> -
跨级通信:使用
provide/inject或 Vuex 状态管理:// 祖先组件 provide() { return { theme: 'dark' } } // 后代组件 inject: ['theme']
插槽与动态组件
-
插槽:通过
<slot>分发内容,支持具名插槽和作用域插槽:<!-- 父组件 --> <template v-slot:header="slotProps"> {{ slotProps.user.name }} </template> <!-- 子组件 --> <slot name="header" :user="user"></slot> -
动态组件:用
<component :is="currentComponent">切换组件。
生命周期与复用
组件生命周期钩子(如 created、mounted)可用于逻辑处理。通过 mixins 或组合式 API(Vue 3 的 setup)实现逻辑复用:
// 组合式 API 示例
import { ref } from 'vue';
export default {
setup() {
const count = ref(0);
return { count };
}
}
注意事项
- 组件命名建议使用帕斯卡命名法(如
MyComponent)。 - 避免直接修改
props,需通过事件通知父组件变更。 - 单文件组件的
<style scoped>可限制样式作用域。






