Vue2:v-model 不支持动态输入类型 [英] Vue2: v-model does not support dynamic input types
问题描述
在尝试创建动态输入元素时,我收到如下模板编译错误:
<块引用>v-model 不支持动态输入类型.使用 v-if 分支相反.
https://jsfiddle.net/u8ncfdvn/
HTML
<sr-el :persons="personsFoo" name="foo" type="number"></sr-el><br><sr-el :persons="personsBar" name="bar" type="text"></sr-el>
JS
Vue.component('sr-el', {模板:`<跨度><input :type="type" :name="name" :id="name" v-model="inputVal" :class="{invalid: !persons}">这是绑定的 {{ name }} 输入值:{{ inputVal }}</span>`,道具:['type', 'name', 'persons'],数据() {返回 {inputVal: this.persons,}}})新的 Vue({el: '#app',数据() {返回 {peopleFoo: 1,人员栏:2,}}})
As of version 2.5.0,Vue 支持动态输入类型,因此您现在可以将 type
绑定到您想要的数据属性:
<小时>对于仍需要使用 2.5 之前版本的任何人:
这个错误的意思是,如果你动态地改变发送给组件的输入类型,Vue 不会更新输入元素来改变它的类型.
你应该使用 v-if
语句来代替:
<input v-if="type == 'number'" type="number" :name="name" :id="name" v-model="inputVal">
When trying to create dynamic input elements i get an template compiling 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's 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,
}
}
})
As of version 2.5.0, Vue supports dynamic input types, so you're now able to bind type
to a data property like you want:
<input :type="type" :name="name" :id="name" v-model="inputVal">
For anyone who still needs to use a version earlier than 2.5:
What this error is saying is that, if you dynamically change the input type being sent to the component, Vue will not update the input element to change its type.
You should use v-if
statements instead:
<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">
这篇关于Vue2:v-model 不支持动态输入类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!