v-model实现数据的双向绑定
数据的双向绑定涉及到v-model
,最近研究了半天才明白其中的原理,先放一段源码出来:
<div id="app">
<p>总数:{{total}}</p>
<my-component v-model="total"></my-component>
<button @click="handleReduce">-1</button>
</div>
<script>
Vue.component('my-component',{
props:['value'],
template:`
<div>
<input :value="value" @input="updataValue">
</div>
`,
methods:{
updataValue:function(event){
this.$emit('input', event.target.value);
}
}
})
var app = new Vue({
el:'#app',
data:{
total:0
},
methods:{
handleReduce:function(){
this.total--;
},
}
});
</script>
数据的双向绑定实现的原理是父组件通过props属性传输数据给子组件,子组件接收后再通过$emit传出数据。
v-model
实质上是个语法糖,实现的语法如下:
<my-component v-model="total"></my-component>
<my-component :value="total" @input="handleGet"></my-component>
// 加入新函数接收
var app = new Vue({
methods:{
handleGet:function(total){
this.total = total;
}
}
});
value
接收了total
的数值,通过props
传输给子组件,子组件再通过@input
监控数据变化,通过$emit传输给自定义的input
函数接收数据,这样就实现了数据的双向绑定。
这个数据双向绑定的难点其实就是关于v-model
语法糖的理解。
顺便再提一下@input
相当于HTML5中的oninput
监听事件。