SoFunction
Updated on 2025-04-05

Example of method for creating high multiplexed components for vue2

1. Use v-bind="$attrs", which is mainly used to automatically pass attributes in the component tree. When a component does not declare any props, it will contain all parent scope bindings. It is equivalent to automatically obtaining the properties used by the parent component.

 <el-button :type="getButtonType" 
    :icon="getIcon"
    v-bind="$attrs" 
    size="small"
   
    class="u-ptype-button">
    <slot></slot>
  </el-button>

2. Use v-on="$listeners",

  • Automatic event listenerv-on="$listeners"The v-on event listeners in the parent scope (excluding .native modifiers) are collected and added to the current component instance.
  • Simplify communication between components: By automatically passing event listeners, the communication between the parent component and the child component is simplified, allowing developers to focus more on the implementation of business logic.
  <el-button :type="getType" 
    :icon="Icons"
    size="small"
    v-on="$listeners"
    class="ptype">
    <slot></slot>
  </el-button>

3. If you want to use the v-model attribute on the child component label

You can use it inside the componentmodelOptions to define:

  • Prop name: This prop is used to receive parent component throughv-modelThe bound value.
  • Event name: When a child component needs to update this value, it triggers an event whose name ismodelIn the optionseventProperty Specifies.
&lt;template&gt;
  &lt;input
    :value="modelValue"
    @input="$emit('update:modelValue', $)"
    type="text"
  /&gt;
&lt;/template&gt;
 
&lt;script&gt;
export default {
  name: 'MyCustomInput',
  props: {
    modelValue: String // The received value is consistent with the prop name bound by v-model  },
  emits: ['update:modelValue'], // Clearly declare the incident issued  model: {
    prop: 'modelValue', // The prop name of the parent component is bound by v-model    event: 'update:modelValue' // Subcomponent triggers to update the event name of v-model  }
}
&lt;/script&gt;
//Subcomponent&lt;MyCustomInput v-model="inputValue" /&gt;
  • Here, v-model="inputValue" will be parsed by Vue to:modelValue="inputValue" @update:modelValue="inputValue = $event".
  • The default prop and event of v-model are modelValue and update:modelValue, respectively. But you can customize them through the component's model options

This is the end of this article about the example method of creating high-reused components in vue2. For more related content on creating high-reused components in vue2, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!