For third-party components, how to elegantly extend the functions while maintaining the original functions of the third-party components (properties, events, slots, methods)?
Take Element Plus’ el-input as an example:
Most likely you have played like this before, encapsulating a MyInput component and putting the props, events and slots to be used . Write the methods again according to your own needs:
// MyInput.vue <template> <div class="my-input"> <el-input v-model="inputVal" :clearable="clearable" @clear="clear"> <template #prefix> <slot name="prefix"></slot> </template> <template #suffix> <slot name="suffix"></slot> </template> </el-input> </div> </template> <script setup> import { computed } from 'vue' const props = defineProps({ modelValue: { type: String, default: '' }, clearable: { type: Boolean, default: false } }) const emits = defineEmits(['update:modelValue', 'clear']) const inputVal = computed({ get: () => props.modelValue, set: (val) => { emits('update:modelValue', val) } }) const clear = () => { emits('clear') } </script>
But after a period of time, the requirements change, and other functions of the el-input component need to be added to the MyInput component. The el-input component has a total of 20 There are multiple attributes, 5 events, and 4 slots. What should we do? Should we pass them in one by one? This is not only cumbersome but also has poor readability.
In Vue2, we can handle it like this, click here to view the encapsulation of Vue third-party components
This article is to help you migrate knowledge and explore how to use Vue3 CompositionAPI to encapsulate elegantly Third-party components~
In Vue2
$attrs: includes the parent role Attribute bindings (except class and style) in the domain that are not recognized (and obtained) as props. When a component does not declare any props, all parent scope bindings (except class and style) will be included here, and internal components can be passed in via v-bind="$attrs"
$listeners: Contains v-on event listeners in the parent scope (excluding .native modifiers). It can pass v-on="$listeners" to pass in internal components
and in Vue3
$attrs: contains the parent role Attribute bindings and events (including class, style and custom events) that are not used as component props or custom events in the domain can also be passed into internal components through v-bind="$attrs".
$listeners object has been removed in Vue 3. Event listeners are now part of $attrs.
The auxiliary function useAttrs in