[英]How to use v-model with multiple in a custom select component?
i have the following vue component 我有以下Vue组件
<template>
<div id="input-div">
<label v-if="label">{{ label }}</label>
<select :multiple="multiple" :value="value" @change="change($event.target.value)">
<slot></slot>
</select>
<div class="error"><slot name="error"></slot></div>
</div>
</template>
<script>
export default {
name: 'ha-select',
props: ['label', 'value', 'multiple'],
methods: {
change(value) {
this.$emit('input', value);
}
}
}
</script>
and since it is a select component i want it to be usable with v-model
which works when the multiple
attribute is not set but when i set multiple pass v-model
an Array instead of appending the selected value to the Array, the array just gets replaced by the value of the current selected option. 并且由于它是一个选择组件,因此我希望它可以与v-model
一起使用,当未设置multiple
属性时,该v-model
可以工作,但是当我将v-model
pass v-model
为Array而不是将所选值附加到Array时,该数组被当前选定选项的值替换。 maybe it has something to do with the way i am emitting the input
event. 也许与我发出input
事件的方式有关。 So how do i create a custom select
component with multiple support? 那么,如何创建具有多种支持的自定义select
组件?
I've modified the code slightly to use a local variable bound to the select with v-model
and emit the bound value. 我已经稍微修改了代码,以使用绑定到带有v-model
的select的局部变量并发出绑定值。 This results in emitting the array of selected values when multiple
is true. 当multiple
为true时,这将导致发出选定值的数组。
console.clear() const CustomSelect = { template: ` <div id="input-div"> <label v-if="label">{{ label }}</label> <select :multiple="multiple" v-model="selected" @change="$emit('input', selected)"> <slot></slot> </select> <div class="error"><slot name="error"></slot></div> </div> `, name: 'ha-select', props: ['label', 'value', 'multiple'], data(){ return { selected:this.value } }, } new Vue({ el:"#app", data:{ albums: [] }, components: { CustomSelect } })
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.js"></script> <div id="app"> <custom-select label="Pink Floyd Albums" v-model="albums" :multiple="true"> <option value="1">Dark Side of the Moon</option> <option value="2">Animals</option> <option value="3">The Wall</option> </custom-select> <div> Selected Albums {{albums}} </div> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.