Given the following Vue 3 higher-order component (HOC) wrapping a base component, what will be rendered?
import { defineComponent, h } from 'vue'; const withWrapper = (BaseComponent) => { return defineComponent({ setup() { return () => h('div', { class: 'wrapper' }, [h(BaseComponent)]); } }); }; const Base = defineComponent({ setup() { return () => h('p', 'Hello from Base'); } }); const Wrapped = withWrapper(Base); // Assume <Wrapped /> is used in template
Think about what the HOC adds around the base component.
The HOC wraps the base component inside a div with class wrapper. So the output includes that wrapper div around the base component's paragraph.
Consider this Vue 3 HOC that adds a counter state to a base component. What is the value of count displayed after clicking the button twice?
import { defineComponent, ref, h } from 'vue'; const withCounter = (BaseComponent) => { return defineComponent({ setup() { const count = ref(0); const increment = () => count.value++; return () => h('div', [ h(BaseComponent, { count: count.value }), h('button', { onClick: increment }, 'Increment') ]); } }); }; const DisplayCount = defineComponent({ props: ['count'], setup(props) { return () => h('p', `Count is: ${props.count}`); } }); const Enhanced = withCounter(DisplayCount); // Assume <Enhanced /> is rendered and user clicks button twice
Each click increases the count by one, starting from zero.
The count state starts at 0 and increments by 1 on each button click. After two clicks, it becomes 2, which is passed as a prop to the base component and displayed.
Which of the following options correctly defines a higher-order component that adds a class prop to the wrapped component?
Consider how to forward attributes and add a class in setup function.
Option A correctly uses the setup function with context to forward all attributes and add a class. Option A ignores attributes, C uses render without context, and A incorrectly uses slots without checking existence.
Given this Vue 3 HOC code, why does it cause a runtime error when used?
import { defineComponent, h } from 'vue'; const withError = (Base) => { return defineComponent({ setup() { // Missing return statement h(Base); } }); };
Remember what the setup function must return in Vue 3 components.
The setup function must return a render function or an object with render. Here, it calls h(Base) but does not return it, so Vue has no render function, causing a runtime error.
Which of the following best describes a key benefit of using higher-order components (HOCs) in Vue 3?
Think about how HOCs help with code reuse and separation of concerns.
HOCs wrap components to add or modify behavior without changing the original component code, enabling logic reuse. They do not automatically memoize, replace Composition API, or enforce runtime typing.