Reputation: 3444
I have a parent component which calls a child component.
The parent :
<select-school-type class="form-control" required value="this.school_type_id" @selected="changeSchoolTypeId">></select-school-type>
The child :
<select v-on:change="$emit('selected', $event.target.value)" v-model="value">
<option value="">{{ placeholder }}</option>
<option :value="schoolType.id" v-for="(schoolType, index) in schoolTypes" :key="index">{{ schoolType.id }}</option>
</select>
The parent can "send" a value to the child (it is the props I called 'value'). And the child must add the "selected" option to the correct item.
I tried a lot of things without success. It is my first components.
Upvotes: 0
Views: 392
Reputation: 446
value="this.school_type_id"
this
is not defined in the template area:
<select-school-type class="form-control" required value="school_type_id" @selected="changeSchoolTypeId"></select-school-type>
If you pass the prop without using:
, (value="school_type_id"
) school_type_id
will be type of string. But here we like to pass the variable school_type_id
→ :value="school_type_id"
v-model
in the child changes the prop value
, which isn't allowed by vue. You should see a warning in the console: "Avoid changing props directly ....". Change it this way and perhaps it works as expected:
<select @change="$emit('selected', $event.target.value)" :selected="value">
<option value="">{{ placeholder }}</option>
<option :value="schoolType.id" v-for="(schoolType, index) in schoolTypes" :key="index">{{ schoolType.id }}</option>
</select>
If you like to use v-model
instead, you can bind a computed getter/setter to it's value: https://v2.vuejs.org/v2/guide/computed.html#Computed-Setter
In the setter, you emit the new value:
computed: {
selectedValue: {
get() {
return this.value;
},
set(newValue) {
this.$emit('selected', newValue);
},
},
},
<select v-model="selectedValue">
<option value="">{{ placeholder }}</option>
<option :value="schoolType.id" v-for="(schoolType, index) in schoolTypes" :key="index">{{ schoolType.id }}</option>
</select>
Upvotes: 1