vue中v-model理解

发布时间 2023-06-13 14:50:58作者: 鱼儿游上天

1.原理

v-model是语法糖,相当于以下代码

<input v-model="value>/>

等价于

<input :value="value" v-on:input="this.value = $event.target.value"/>
  • v-bind:value实现数据从data->组件
  • input触摸事件实现数据从组件->data

v-model 在内部为不同的输入元素使用不同的属性并抛出不同的事件:
text 和 textarea 元素使用 value 属性和 input 事件;
checkbox 和 radio 使用 checked 属性和 change 事件;
select 字段将 value 作为 prop 并将 change 作为事件。
从而实现双向绑定

2.使用

2.1 使用在组件上时

  • 注意
    为了让它正常工作,这个组件内的 必须:
    将其 value attribute 绑定到一个名叫 value 的 prop 上
    在其 input 事件被触发时,将新的值通过自定义的 input 事件抛出
<custom-input
  v-bind:value="searchText"
  v-on:input="searchText = $event"
></custom-input>

Vue.component('custom-input', {
  props: ['value'],
  template: `
    <input
      v-bind:value="value"
      v-on:input="$emit('input', $event.target.value)"
    >
  `
})
<custom-input v-model="searchText"></custom-input>

2.2 model属性

一个组件上的 v-model 默认会利用名为 value 的 prop 和名为 input 的事件,但是像单选框、复选框等类型的输入控件可能会将 value attribute 用于不同的目的。model 选项可以用来避免这样的冲突

Vue.component('base-checkbox', {
  model: {
    prop: 'checked',
    event: 'change'
  },
  props: {
    checked: Boolean
  },
  template: `
    <input
      type="checkbox"
      v-bind:checked="checked"
      v-on:change="$emit('change', $event.target.checked)"
    >
  `
})