0👍
Don’t bind both v-model
and :value
They are both trying to control the same underlying feature.
Debugging
I see your remark that just using v-model doesn’t work.
Change your code to show some debugging information:
<template>
<div>
<p>defaultValue is: {{defaultValue}}</p>
<p>value is: {{value}}</p>
<multiselect
v-model="value"
...
</multiselect>
</div>
</template>
The reason this is important, is that we currently don’t know what values are being fed into this component inside this.defaultValue
.
We can see this:
<MyComponent other things... :defaultValue="station"/>
but we don’t know what the value of the variable this.station
in your parent component is. It might not be one of the possible values of multiselect.
The debugging step will help resolve that.
0👍
You need to give defaultvalue
a default value in your component, specifically you can have two ways:
You can pass a non-null value using the parent component.
or
Use the watch method to monitor your defaultvalue
, and when it is empty, give defaultvalue
a default value.
parent component:
<multi-select :default-value="selectValue" />
data() {
return {
selectValue: '', // you can set null or '' or '1' or '3' or '2'
};
}
child component:
<select v-model="selectValue">
<option
v-for="(item, index) in selectArray"
:key="index"
:value="item.value"
>
{{ item.label }}
</option>
</select>
export default {
name: 'MultiSelect',
props: {
defaultValue: String,
},
data() {
return {
selectArray: [
{ value: '1', label: 'Value 1' },
{ value: '2', label: 'Value 2' },
{ value: '3', label: 'Value 3' },
],
};
},
computed: {
selectValue: {
get() {
if (!this.defaultValue) {
return '1';
}
return this.defaultValue
},
set(newVal) {
console.log(newVal);
},
},
},
}