Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue2: v-model does not support dynamic input types

Tags:

vue.js

vuejs2

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,
    }
  }
})
like image 391
Mike Avatar asked May 18 '26 05:05

Mike


1 Answers

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">

Here's a working fiddle.


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">
like image 161
thanksd Avatar answered May 20 '26 21:05

thanksd