简体   繁体   中英

Custom wrapper component with props and v-model

I am using the vue-select library: https://github.com/desislavsd/vue-select in my app.

Since I am using a lot of them I just want to make a separate wrapper component, but now my selects don't work. Vue somehow doesn't recognize the props. How can I make my v-select a separate reusable component that can accept it's normal props and worK?

This is my Select component:

<template>
    <div>
        <v-select/>
    </div>
</template>

<script>
export default {
    name: "Select",
}
</script>

And this is how I am using it:

<Select as="role" placeholder="Assesor" v-model="value1" :from="roles"  :key="roles.role" />

export default {
  name: "Admin",
  components: {
    Header,
    Select
  },
  data() {
    return {
      value1: [],
      selected: {
       role: ''
      },
      roles: [
        { role: "Assesors" },
        { role: "Finance" },
        { role: "Sales" }
      ]
    };
  }
};

This is more complex than it seems. You expect the props passed to the custom component to be applied to the inner v-select but Vue doesn't know that. Someone else might expect them to go on the <div> .

v-bind="$attrs"

Props are not automatically passed to a child element. To do that, you need:

<v-select v-bind="$attrs" />

v-model

Now the props are applied to the element you choose. But since v-model is a special prop from the parent with hidden functionality, it's not passed properly without some extra preparation. You'll have to code a v-model directly on the child:

<v-select v-bind="$attrs" v-model="model" />

Computed setter

The parent's v-model passes down a value prop. Create a computed setter in the custom element (I'm calling it model ) to use with the child's v-model :

computed: {
  model: {
    get() { return this.$attrs.value },
    set(val) { this.$emit('input', val) }
  }
}

Here is the updated demo with a custom wrapper component using selected and as="role::role"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM