vue2进阶之v-model在组件上的使用

v-model 用在 input 元素上时

v-model虽然很像使用了双向数据绑定的 Angular 的 ng-model,但是 Vue 是单项数据流,v-model 只是语法糖而已:

<input v-model="sth" />
<input v-bind:value="sth" v-on:input="sth = $event.target.value" />

第一行的代码其实只是第二行的语法糖

我们仔细观察语法糖和原始语法那两行代码,可以得出一个结论:

在给 <input /> 元素添加 v-model 属性时,默认会把 value 作为元素的属性,然后把 'input' 事件作为实时传递 value 的触发事件

v-model 用在组件上时

v-model 不仅仅能在 input上用,在组件上也能使用,下面是一个和 Vue 官网教程类似的例子(在看这个例子时我们要考虑两个问题):

<div id="demo">
 <currency-input v-model="price"></currentcy-input>
 <span>{{price}}</span>
</div>
<script src="https://cdn.bootcss.com/vue/2.3.0/vue.js"></script>
<script>
Vue.component('currency-input', {
 template: `
  <span>
   <input
    ref="input"
    :value="value"
    <!--为什么这里把 'input' 作为触发事件的事件名?`input` 在哪定义的?-->
    @input="$emit('input', $event.target.value)"
   >
  </span>
 `,
 props: ['value'],// 为什么这里要用 value 属性,value在哪里定义的?貌似没找到啊?
})
 
var demo = new Vue({
 el: '#demo',
 data: {
  price: 100,
 }
})
</script>

如果你知道这两个问题的答案,那么恭喜你真正掌握了 v-model,如果你没明白,那么可以看下这段代码:

<currency-input v-model="price"></currentcy-input>
<!--上行代码是下行的语法糖
 <currency-input :value="price" @input="price = arguments[0]"></currency-input>
-->

现在你知道 value 和 input 从哪来的了吧。与上面总结的类似:

给组件添加 v-model 属性时,默认会把 value 作为组件的属性,然后把 'input' 值作为给组件绑定事件时的事件名

猜你喜欢

转载自www.cnblogs.com/raind/p/9277050.html