<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdn.staticfile.org/vue/2.6.12/vue.min.js"></script>
</head>
<body>
<div id="app">
<h2>父组件:</h2>
<p>num1: {{num1}}</p>
<p>num2: {{num2}}</p>
<cpn @dnm1='dnm1' @dnm2='dnm2'
:pnum1='num1' :pnum2='num2'
/>
</div>
<template id="cpn">
<div>
<h2>子组件props:</h2>
<p>pnum1: {{pnum1}}</p>
<p>pnum2: {{pnum2}}</p>
<h2>子组件data:</h2>
<p>请输入:</p>
input1 <input type="text" :value="dnum1" @input='change1'><br>
input2 <input type="text" :value="dnum2" @input='change2'>
<p>dnum1: {{dnum1}}</p>
<p>dnum2: {{dnum2}}</p>
</div>
</template>
<script>
const cpn = {
template: '#cpn',
data() {
return {
dnum1: this.pnum1,
dnum2: this.pnum2
}
},
props: {
pnum1: Number,
pnum2: Number
},
methods: {
change1(event) {
this.dnum1 = event.target.value;
this.dnum2 = 100*this.dnum1;
this.$emit('dnm2',this.dnum2)
this.$emit('dnm1',this.dnum1)
},
change2(event) {
this.dnum2 = event.target.value;
this.dnum1 = this.dnum2/100;
this.$emit('dnm1',this.dnum1)
this.$emit('dnm2',this.dnum2)
}
}
}
const vm=new Vue({
el:'#app',
data:{
num1: 0,
num2: 1
},
methods:{
dnm1(value) {
this.num1 = value
},
dnm2(value) {
this.num2 = value
}
},
components: {
cpn
}
});
</script>
</body>
</html>
input 输入=>子组件data同步更新,并传入@input事件,利用事件$emit=>父组件=>子组件props No2=No1*100