vue中组件实现
Vue 组件实现方法
全局注册组件
通过 Vue.component() 方法全局注册组件,在任何 Vue 实例中均可使用。注册时需指定组件名称和配置对象:
Vue.component('my-component', {
template: '<div>全局组件内容</div>'
});
局部注册组件
在 Vue 实例或组件的 components 选项中局部注册,仅当前作用域可用:
const MyComponent = {
template: '<div>局部组件内容</div>'
};
new Vue({
el: '#app',
components: { 'my-component': MyComponent }
});
单文件组件(SFC)
使用 .vue 文件组织组件,包含模板、逻辑和样式:
<template>
<div>{{ message }}</div>
</template>
<script>
export default {
data() {
return { message: '单文件组件示例' };
}
};
</script>
<style scoped>
div { color: red; }
</style>
动态组件
通过 <component :is="currentComponent"> 实现动态切换组件,需配合 keep-alive 缓存状态:
<keep-alive>
<component :is="currentTabComponent"></component>
</keep-alive>
异步组件
使用 import() 语法实现按需加载,提升应用性能:
Vue.component('async-component', () => import('./AsyncComponent.vue'));
组件通信
- Props 向下传递:父组件通过属性传递数据
<child-component :prop-name="parentData"></child-component> - $emit 向上通知:子组件触发事件
this.$emit('event-name', payload); - Provide/Inject:跨层级数据传递
provide() { return { theme: this.theme } }, inject: ['theme']
插槽(Slots)
- 默认插槽:
<slot>后备内容</slot> - 具名插槽:
<slot name="header"></slot> - 作用域插槽:
<slot :item="item"></slot>
渲染函数
通过 render 函数直接生成虚拟 DOM,适用于复杂动态场景:
render(h) {
return h('div', this.$slots.default);
}






