已更新至父子之间的双向通信

This commit is contained in:
Code12121 2022-10-31 18:08:03 +08:00
parent 4ae3ea6ce5
commit 2a1dcc8dfb
1 changed files with 95 additions and 0 deletions

View File

@ -0,0 +1,95 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<!--
本案例实现了父子组件之间的双向绑定
注意点:
1、修改值时不能直接绑定props否则会导致数据错乱
2、记得分清楚哪一个是父组件哪一个是子组件重要
3、$emit所发射的内容必须要由父组件的v-on事件所接受
-->
<div id="app" >
<apps :num-befor1="num1" :num-befor2="num2" @this_data_n1="this_num1" @this_data_n2="this_num2"></apps>
</div>
<template id="tpl">
<div>
<h1>Props:{{numBefor1}}</h1>
<h1>Data_n1:{{Data_n1}}</h1>
<input type="text" name="" id="" :value="Data_n1" @input="Data_num1" >
<h1>Props:{{numBefor2}}</h1>
<h1>Data_n2:{{Data_n2}}</h1>
<input type="text" name="" id="" :value="Data_n2" @input="Data_num2">
<!-- <input type="text" name="" id="" v-model="numBefor1">
不能直接绑定父传子的prop属性相反要绑定在data或者computed属性-->
</div>
</template>
</body>
<script src="../../JavaScript/vue.js"></script>
<script>
new Vue({
el:"#app",
data:{
num1:1,
num2:1
},
methods:{
this_num1(val){
this.num1=val*1
},
this_num2(val){
this.num2=parseInt(val)
},
this_Data_n2(val){
this.num2=val
},
this_Data_n1(val) {
this.num1 = val
}
},
components:{
'apps':{
template:"#tpl",
data(){
return{
Data_n1:this.numBefor1,
Data_n2: this.numBefor2
}
},
props:{
'numBefor1':{
type:Number,
default(){
return 0
}
},
'numBefor2':{
type: Number,
default() {
return 0
}
},
},
methods: {
Data_num1(val) {
this.Data_n1=val.target.value
this.$emit("this_data_n1",this.Data_n1)
this.Data_n2=this.Data_n1*100
},
Data_num2(val) {
this.Data_n2 = val.target.value
this.$emit("this_data_n2", this.Data_n2)
this.Data_n1=this.Data_n2/100
}
}
}
}
})
</script>
</html>