vue实现高阶组件
Vue 高阶组件实现方法
高阶组件(HOC)是一种复用组件逻辑的模式,通过函数包裹组件并返回新组件实现。Vue 中可通过以下方式实现:
使用 render 函数
通过函数接收组件选项并返回新组件选项:

function withLoading(WrappedComponent) {
return {
data() {
return { isLoading: false }
},
render(h) {
return h('div', [
h(WrappedComponent, {
props: this.$attrs,
on: this.$listeners
}),
this.isLoading ? h('div', 'Loading...') : null
])
}
}
}
使用 mixins
通过混入方式扩展组件功能:
const withLogging = {
mounted() {
console.log('Component mounted')
}
}
const EnhancedComponent = {
mixins: [withLogging],
template: '<div>Enhanced Component</div>'
}
使用插槽
通过作用域插槽实现逻辑复用:

const DataProvider = {
data() {
return { data: null }
},
render(h) {
return this.$scopedSlots.default({
data: this.data
})
}
}
使用 provide/inject
通过依赖注入共享状态:
const ThemeProvider = {
provide() {
return { theme: 'dark' }
},
render(h) {
return h('div', [this.$slots.default])
}
}
const ThemedButton = {
inject: ['theme'],
template: '<button :class="theme">Button</button>'
}
组合式 API 实现
使用 setup 函数和 hooks:
import { ref } from 'vue'
function useCounter() {
const count = ref(0)
const increment = () => count.value++
return { count, increment }
}
const Counter = {
setup() {
const { count, increment } = useCounter()
return { count, increment }
},
template: `
<button @click="increment">
Count: {{ count }}
</button>
`
}
注意事项
- 正确处理 $attrs 和 $listeners 确保属性和事件传递
- 避免直接修改原组件,应通过包装方式扩展
- 命名冲突需谨慎处理,建议使用命名空间
- 性能优化需考虑,避免不必要的重新渲染
以上方法可根据具体场景选择,组合式 API 方式在 Vue 3 中更为推荐。






