Vue2: v-model doesn't support dynamic input types
When trying to create dynamic input elements, I get a template compilation error like this:
v-model does not support dynamic input types. Use v-if branches instead.
https://jsfiddle.net/u8ncfdvn/
Html
<div id="app">
<sr-el :persons="personsFoo" name="foo" type="number"></sr-el>
<br>
<sr-el :persons="personsBar" name="bar" type="text"></sr-el>
</div>
Js
Vue.component('sr-el', {
template: `
<span>
<input :type="type" :name="name" :id="name" v-model="inputVal" :class="{invalid: !persons}">
Here the bound {{ name }} input value: {{ inputVal }}
</span>
`,
props: ['type', 'name', 'persons'],
data() {
return {
inputVal: this.persons,
}
}
})
new Vue({
el: '#app',
data() {
return {
personsFoo: 1,
personsBar: 2,
}
}
})
+3
source to share
1 answer
Since version 2.5.0 , Vue supports dynamic input types, so now you can bind type
to data however you want:
<input :type="type" :name="name" :id="name" v-model="inputVal">
For those who still need to use a version earlier than 2.5:
This error says that if you dynamically change the input type being sent to the component, Vue will not update the input element to change its type.
Operators should be used instead v-if
:
<input v-if="type == 'text'" type="text" :name="name" :id="name" v-model="inputVal">
<input v-if="type == 'number'" type="number" :name="name" :id="name" v-model="inputVal">
+4
source to share