简体   繁体   English

带有 props 和 v-model 的自定义包装组件

[英]Custom wrapper component with props and v-model

I am using the vue-select library: https://github.com/desislavsd/vue-select in my app.我在我的应用程序中使用vue-select库: https://github.com/desislavsd/vue-select

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. Vue 不知何故无法识别道具。 How can I make my v-select a separate reusable component that can accept it's normal props and worK?如何使我的v-select成为一个单独的可重用组件,它可以接受它的正常道具和工作?

This is my Select component:这是我的 Select 组件:

<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.您希望传递给自定义组件的 props 应用于内部v-select ,但 Vue 不知道这一点。 Someone else might expect them to go on the <div> .其他人可能希望他们在<div>上使用 go 。

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.但是由于v-model是来自父级的具有隐藏功能的特殊道具,因此如果没有一些额外的准备,它就不会正确传递。 You'll have to code a v-model directly on the child:您必须直接在孩子身上编写一个v-model

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

Computed setter计算二传手

The parent's v-model passes down a value prop.父级的v-model传递一个value prop。 Create a computed setter in the custom element (I'm calling it model ) to use with the child's v-model :在自定义元素中创建一个计算设置器(我称之为model )以与孩子的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"这是使用selectedas="role::role"的自定义包装器组件的更新演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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