v-model数据绑定原理:v-model封装了v-bind和v-on两个指令,当值改变时首先通过v-on触发事件并改变组件的值,然后使用v-bind将输入框的值保存起来。在高版本的vue【测试为2.6+】中,不需要使用v-bind属性来保存值。
样例说明:
父组件data中的num1、num2绑定给了子组件,在子组件的输入框中改变子组件值,同时会利用输入框的input事件改变子组件data中的值,然后同过$emit触发父组件事件改变num1、num2。值1与值2是1:10的关系。
代码:
<div id="app">
<h2>num1: {{num1}}</h2>
<h2>num2: {{num2}}</h2>
<hr>
<cpn :sub_pro_num1="num1"
:sub_pro_num2="num2"
@modify_num1 = "modify_num1"
@modify_num2 = "modify_num2"
></cpn>
</div>
<template id="tem">
<div>
<h2>子组件值1(props中):{{sub_pro_num1}}</h2>
<h2>子组件值1(data中):{{sub_num1}}</h2>
<!-- <input type="text" v-model="sub_num1"> warn! -->
<input type="text" :v="sub_num1" @input="sub_num1_fn">
<h2>子组件值2(props中):{{sub_pro_num2}}</h2>
<h2>子组件值2(data中):{{sub_num2}}</h2>
<!-- <input type="text" v-model="sub_num2"> warn! -->
<input type="text" :v="sub_num2" @input="sub_num2_fn">
</div>
</template>
<script>
var vm = new Vue({
el:"#app",
data:{
num1:1,
num2:0,
},
methods:{
modify_num1(val){
this.num1 =val;
},
modify_num2(val){
this.num2 = val;
}
},
components:{
"cpn":{
template:`#tem`,
props:{
sub_pro_num1:Number,
sub_pro_num2:Number,
},
data(){
return{
sub_num1:this.sub_pro_num1,
sub_num2:this.sub_pro_num2,
}
},
methods:{
sub_num1_fn(event){
this.sub_num1 = parseFloat(event.target.value);
this.sub_num2 = this.sub_num1*10;
this.$emit("modify_num1",this.sub_num1);
this.$emit("modify_num2",this.sub_num2);
},
sub_num2_fn(event){
this.sub_num2 = parseFloat(event.target.value);
this.$emit("modify_num2",this.sub_num2);
this.sub_num1 = this.sub_num2/10;
this.$emit("modify_num1",this.sub_num1);
}
}
}
}
});
</script>