[Vuejs]-Which limitations v-model has in Vue 2.x?

2👍

v-model="formData" === v-bind:value="formData" v-on:input="formData = $event.target.value". It’s not a magic command that does everything, but a shorter way to write a basic functionality.

To get the behaviour you need, you have to write your own components that take the value and do something with it.

To chain v-model between multiple layers of components, you want to $emit the new data rather than the default behaviour of changing the components’ state. The easiest way to do this is by using a computed getter/setter. I use the code below to pass through anything from simple values to entire objects to custom input components that handle the binding to different html inputs.

--- ParentTemplate:
<Child v-model="formData"></Child>

-- ChildTemplate:
<input v-model="localValue">

-- ChildScript:
computed: {
    localValue: {
      get() {
        return this.value;
      },
      set(localValue) {
        this.$emit('input', localValue);
      },
    },
  },

If you need to convert data from an input before it’s sent out (eg formatting), you can use a computed value or method to transform the data before you $emit it in the setter.

Leave a comment