Use of V-model syntax sugar

When using v-Model for two-way data binding:

<input v-model="something">
Copy the code

Just a grammatical sugar:

<input v-bind:value="something" v-on:input="something=$event.target.value">
Copy the code

So when used in a component, it is equivalent to the following shorthand:

<custom v-bind:value="something" v-on:input="something = $event.target.value"></custom>
Copy the code

So for the component’s V-Model to work, it must:

  • Accept a value attribute

  • The input event is raised when a new value is present

Contrast:

<template>
  <InputNumber v-model="value" />
</template>
<script>
  import InputNumber from '.. /components/input-number/input-number.vue';

  export default {
    components: { InputNumber },
    data () {
      return {
        value: 1
      }
    }
  }
</script>
Copy the code
<template>
  <InputNumber :value="value" @input="handleChange" />
</template>
<script>
  import InputNumber from '.. /components/input-number/input-number.vue';

  export default {
    components: { InputNumber },
    data () {
      return {
        value: 1
      }
    },
    methods: {
      handleChange (val) {
        this.value = val;
      }
    }
  }
</script>
Copy the code