i have the following vue component
<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. maybe it has something to do with the way i am emitting the input
event. So how do i create a custom select
component with multiple support?
I've modified the code slightly to use a local variable bound to the select with v-model
and emit the bound value. This results in emitting the array of selected values when multiple
is 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>
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.