A higher-order component (HOC) is a way to reuse component logic by wrapping one component inside another. It helps keep your code clean and organized.
0
0
Higher-order components concept in Vue
Introduction
When you want to add the same behavior or data to many components without repeating code.
When you need to share common logic like loading data or handling errors across components.
When you want to enhance a component with extra features like tracking user actions.
When you want to separate concerns by keeping UI and logic apart.
When you want to wrap a component to add styling or layout without changing its code.
Syntax
Vue
const EnhancedComponent = (BaseComponent) => { return { components: { BaseComponent }, setup(props, { attrs, slots }) { // shared logic here return () => h(BaseComponent, { ...attrs }, slots) } } }
The HOC is a function that takes a component and returns a new component.
Use h() to render the wrapped component inside the new one.
Examples
This HOC logs a message every time the wrapped component renders.
Vue
const withLogger = (BaseComponent) => { return { setup(props, { attrs, slots }) { return () => { console.log('Component rendered') return h(BaseComponent, { ...attrs }, slots) } } } }
This HOC shows a loading message before displaying the wrapped component.
Vue
const withLoading = (BaseComponent) => { return { data() { return { loading: true } }, mounted() { setTimeout(() => { this.loading = false }, 2000) }, render() { if (this.loading) return h('div', 'Loading...') return h(BaseComponent, this.$attrs, this.$slots) } } }
Sample Program
This example creates a higher-order component withBorder that adds a blue border around any component it wraps. We wrap SimpleMessage to get BorderedMessage which shows the message inside a bordered box.
Vue
<script setup> import { h } from 'vue' const withBorder = (BaseComponent) => { return { setup(props, { attrs, slots }) { return () => h('div', { style: { border: '2px solid blue', padding: '1rem' } }, [ h(BaseComponent, { ...attrs }, slots) ]) } } } const SimpleMessage = { props: ['msg'], template: `<p>{{ msg }}</p>` } const BorderedMessage = withBorder(SimpleMessage) </script> <template> <BorderedMessage msg="Hello from HOC!" /> </template>
OutputSuccess
Important Notes
HOCs help keep your code DRY (Don't Repeat Yourself) by sharing logic.
Remember to pass props and slots correctly to the wrapped component.
Vue 3 uses h() function to create elements inside setup or render functions.
Summary
Higher-order components wrap other components to add shared logic or styling.
They are functions that return new components wrapping the original ones.
Use HOCs to keep your Vue app clean and reusable.