v-model实际上就是,v-bind和v-on的集合

  1. <input type="text" :value="msg" @input="msg = $event.target.value" />

以上代码等同于:

  1. <input type="text" v-model="msg" />

必要条件:

  1. v-bind必须是”value”,:value
  2. v-on监听的事件必须是”input” ,@input

    组件间使用v-model

    父组件

  • 分解为v-bind和v-on的形式

    1. <HelloWorld :value="fatherData" @input="subInuput" />
    2. ...
    3. methods: {
    4. subInuput(val) {
    5. this.fatherData = val
    6. }
    7. }
  • 以上代码就可以改写为

    1. <HelloWorld v-model="fatherData" />

    子组件

  • 根据父组件的传参,子组件需要接收value,以及向父组件发送一个名为”input”的自定义事件

  • 注意:这里emit传递的参数需要是你要改变的结果
    1. <input type="text" :value="value" @input="$emit('input', $event.target.value)" />
    2. ...
    3. props:['value']