实现思路:pro拿到父组建的数据并实例化 子组建中的data,再通过v-model 这里 v-model 不方便就用 :value 和 @input 绑定输入的值和更改的值。这样模板中的data就被修改了,pro改起来麻烦一点,其是父组建传下来的值,想要更改就要让子组件通过$emit 传出更改的data值,父组件接受值后 ,更改其data中的数据这样模板中子组件的data值也响应更改了.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<template id='cpnn'>
<div>
<h2>pro:{{num1}}</h2>
<h2>data:{{dnum1}}</h2>
<input type="text" :value='dnum1' @input="getd1">
<br>
<input type="text" :value='dnum2' @input="getd2">
<h2>pro:{{num2}}</h2>
<h2>data:{{dnum2}}</h2>
</div>
</template>
<div id="app">
<cpn :num1="message1"
:num2="message2"
@ddn1="getM1"
@ddn2="getM2"></cpn>
</div>
<script src="../js/vue.js"></script>
<script>
const v=new Vue({
el:'#app',
data:{
message1:0,
message2:0,
},
methods:{
getM1(value){
this.message1= parseFloat(value)
},
getM2(v){
this.message2=parseFloat(v)
}
},
components:{
cpn:{
template:'#cpnn',
props:{
num1:Number,
num2:Number
},
data(){
return{
dnum1:this.num1,
dnum2:this.num2
}
},
methods:{
getd1(event){
this.dnum1=event.target.value
this.$emit('ddn1',this.dnum1)
},
getd2(event){
this.dnum2=event.target.value
this.$emit('ddn2',this.dnum2)
}
}
}
}
})
</script>
</body>
</html>