vue怎么实现组件复用
实现组件复用的方法
使用 props 传递数据
通过 props 将数据从父组件传递给子组件,子组件接收数据并渲染。这种方式适用于静态或动态数据的传递。
<!-- 父组件 -->
<template>
<ChildComponent :title="parentTitle" />
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: { ChildComponent },
data() {
return { parentTitle: 'Hello' };
}
};
</script>
<!-- 子组件 -->
<template>
<h1>{{ title }}</h1>
</template>
<script>
export default {
props: ['title']
};
</script>
使用插槽(Slots)
插槽允许父组件向子组件插入内容,实现更灵活的复用。
<!-- 父组件 -->
<template>
<ChildComponent>
<p>插入的内容</p>
</ChildComponent>
</template>
<!-- 子组件 -->
<template>
<div>
<slot></slot>
</div>
</template>
使用作用域插槽(Scoped Slots)
作用域插槽允许子组件向插槽传递数据,父组件决定如何渲染。

<!-- 子组件 -->
<template>
<div>
<slot :item="itemData"></slot>
</div>
</template>
<script>
export default {
data() {
return { itemData: { name: 'Vue' } };
}
};
</script>
<!-- 父组件 -->
<template>
<ChildComponent>
<template v-slot:default="slotProps">
<p>{{ slotProps.item.name }}</p>
</template>
</ChildComponent>
</template>
使用 mixins 复用逻辑
mixins 可以将公共逻辑抽离,多个组件共享相同的方法或数据。
// mixin.js
export const myMixin = {
data() {
return { count: 0 };
},
methods: {
increment() {
this.count++;
}
}
};
// 组件中使用
<script>
import { myMixin } from './mixin.js';
export default {
mixins: [myMixin]
};
</script>
使用自定义指令或插件
通过全局注册自定义指令或插件,实现跨组件的功能复用。

// 自定义指令
Vue.directive('focus', {
inserted(el) {
el.focus();
}
});
// 插件
const MyPlugin = {
install(Vue) {
Vue.prototype.$myMethod = () => console.log('Plugin method');
}
};
Vue.use(MyPlugin);
通过 provide/inject 跨层级传递数据
父组件通过 provide 提供数据,子孙组件通过 inject 获取数据,适合深层嵌套的组件复用。
// 父组件
export default {
provide() {
return { theme: 'dark' };
}
};
// 子孙组件
export default {
inject: ['theme']
};
组合式 API 复用逻辑
使用 Vue 3 的 setup 和 composables 将逻辑抽离为可复用的函数。
// useCounter.js
import { ref } from 'vue';
export function useCounter() {
const count = ref(0);
const increment = () => count.value++;
return { count, increment };
}
// 组件中使用
<script>
import { useCounter } from './useCounter.js';
export default {
setup() {
const { count, increment } = useCounter();
return { count, increment };
}
};
</script>






