v-model本质上为语法糖
<input v-model="personName">
等价于
<input v-bind:value="personName" v-on:input="personName = $event.target.value">
但在遇到input[type="checkbox"]等非输入内容的input时,绑定的内容又不太一样,具体参见官网
同时还可以这么等价:
<input v-bind:value="personName" v-on:input="personName = arguments[0]">
其中arguments对象是所有(非箭头)函数中都可用的局部变量,引用的是函数的参数,arguments[0]代表函数的第一个形参,在这里也就代表input事件函数传入的参数。关于arguments可以看看这里
如果把v-model放到自定义的组件上:
<base-input v-model="person"></base-input>
等价于
<base-input v-bind:value="person" v-on:input="person = arguments[0]"></base-input>
如果想要这个组件上的v-model生效,则组件需要这么写:
Vue.component('base-input', {
template: `
<input
type="text"
v-bind:value="value"
v-on:input="$emit('input', $event.target.value)">`,
props: {
value: String
}
});
原理是通过props.value接收v-bind-value传来的person值,然后通过input的input事件触发原生事件并传递value,从而达到v-model在input上使用的效果。
如果设置了model选项,则这个控件可以表述地更清楚:
Vue.component('base-input', {
template: `
<input
type="text"
v-bind:value="person"
v-on:input="$emit('my-event', $event.target.value)">`,
props: {
value: String
},
model: {
prop: 'person',
event: 'my-event' // 这个事件一旦不是value,那么显示出来的input输入框内就不会出现预定义的值了
}
});
这么使用:
<div id="app">
<base-input v-model="person"></base-input>
<span>{{ person }}</span>
</div>