vue怎能实现组件复用
Vue 实现组件复用的方法
使用 props 传递数据
父组件通过 props 向子组件传递数据,子组件接收并渲染。这种方式适合静态或动态数据的传递,确保组件逻辑独立。
<!-- 父组件 -->
<ChildComponent :title="parentTitle" />
<!-- 子组件 -->
<script>
export default {
props: ['title']
}
</script>
通过插槽(slot)复用内容
插槽允许父组件向子组件插入任意内容,实现布局复用。具名插槽可精准控制插入位置。

<!-- 子组件 -->
<template>
<div>
<slot name="header"></slot>
<slot></slot>
</div>
</template>
<!-- 父组件 -->
<ChildComponent>
<template v-slot:header>
<h1>自定义标题</h1>
</template>
<p>自定义内容</p>
</ChildComponent>
利用 mixins 复用逻辑
将公共逻辑提取为 mixin,多个组件通过混入共享相同的方法、生命周期钩子等。
// mixin.js
export const myMixin = {
methods: {
sharedMethod() {
console.log('复用方法');
}
}
}
// 组件中使用
import { myMixin } from './mixin.js';
export default {
mixins: [myMixin]
}
使用自定义指令或过滤器
针对重复的 DOM 操作或数据格式化,可通过自定义指令或过滤器实现复用。

// 全局过滤器
Vue.filter('dateFormat', value => {
return new Date(value).toLocaleString();
});
// 使用
{{ timestamp | dateFormat }}
高阶组件(HOC)模式
通过函数包裹组件,返回增强后的新组件。适合逻辑复杂且需多层级复用的场景。
function withLogging(WrappedComponent) {
return {
mounted() {
console.log('组件已挂载');
},
render(h) {
return h(WrappedComponent);
}
};
}
组合式 API(Composition API)
Vue 3 的 setup 函数允许将逻辑抽离为可复用的函数,通过导入方式在多个组件中使用。
// useCounter.js
import { ref } from 'vue';
export function useCounter() {
const count = ref(0);
const increment = () => count.value++;
return { count, increment };
}
// 组件中使用
import { useCounter } from './useCounter';
export default {
setup() {
const { count, increment } = useCounter();
return { count, increment };
}
}






