Trying to incorporate a select element into a Vue custom component using the v-model
pattern outlined in the documentation.
The issue at hand is encountering an error message for the custom select component:
[Vue warn]: Avoid directly mutating a prop as its value will be overwritten during parent component re-renders. Instead, utilize a data or computed property based on the prop's value. The prop being mutated: "value"
found within
--->
However, converting value
into a data property leads to loss of expected functionality where the select box does not update upon value changes, causing a loss of two-way binding.
What is the proper approach to maintain the intended behavior without triggering warnings?
See below for an interactive demonstration showcasing the problem (best viewed in full screen).
Vue.component('dynamic-select-ex1', {
template: '#dynamic-select-template',
props: ['value', 'options'],
methods: {
changed() {
// Custom input components should emit the input event
this.$emit('input', event.target.value)
},
},
})
Vue.component('dynamic-select-ex2', {
template: '#dynamic-select-template',
props: ['options'],
data() {
return {
value: null,
}
},
methods: {
changed() {
// Custom input components should emit the input event
this.$emit('input', event.target.value)
},
},
})
let example = new Vue({
el: '#example',
data() {
return {
selected: null,
options: [
{ text: 'Hello', value: 1 },
{ text: 'World', value: 2 },
{ text: 'Blah', value: 3 },
{ text: 'Blerg', value: 4 },
]
}
},
computed: {
text() {
if (!this.selected) return
return this.options.find(({ value }) => value == this.selected).text
},
},
methods: {
select(value) {
this.selected = value
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script type="text/x-template" id="dynamic-select-template">
<select v-model="value" @change="changed">
<option v-for="option in options" :value="option.value">{{ option.text }}</option>
</select>
</script>
<div id="example">
<label for="direct">Vue behaviour for native select</label><br>
<select id="direct" v-model="selected">
<option v-for="option in options" :value="option.value">{{ option.text }}</option>
</select><br>
<div>Vue behaviour for custom component. `value` is a prop. Warning output in console when user selects option</div>
<dynamic-select-ex1 v-model="selected" :options="options"></dynamic-select-ex1><br>
<div>Vue behaviour for custom component. `value` is a data property. Two-way binding is broken. Selected option not updated when `value` changes.</div>
<dynamic-select-ex2 v-model="selected" :options="options"></dynamic-select-ex2><br>
<br>Selected: {{ text }}<br><br>
<button @click="select(1)">Hello</button>
<button @click="select(2)">World</button>
<button @click="select(3)">Blah</button>
<button @click="select(4)">Blerg</button><br>
</div>