admin-vue/10-组件化开发/07-父子组件的通信/父子组件所进行的互相通信.html

97 lines
2.5 KiB
HTML
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<!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" @this_bedata1="this_Data1"></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_bedata1(val){
this.num1=val
},
this_bedata2(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
this.$emit("this_bedata2", Data_n2)
},
Data_num2(val) {
this.Data_n2 = val.target.value
this.$emit("this_data_n2", this.Data_n2)
this.Data_n1=this.Data_n2/100
this.$emit("this_bedata1", Data_n1)
}
}
}
}
})
</script>
</html>