案例最终效果如下:
主要解决父子组件之间的传值,以及子组件如何"修改"父组件data的问题。主要代码片段如下:
<!-- 父组件 -->
<div id="app">
<cpn :number1="num1"
:number2="num2"
@num1change="num1change"
@num2Change="num2Change"
/>
</div>
<!-- 子组件 -->
<template id="cpn">
<div>
<h2>props:{{number1}}</h2>
<h2>data:{{dnumber1}}</h2>
<!-- <input type="text" v-model="dnumber1"> -->
<input type="text" :value="dnumber1" @input="num1Input">
<h2>props:{{number2}}</h2>
<h2>data:{{dnumber2}}</h2>
<!-- <input type="text" v-model="dnumber2"> -->
<input type="text" :value="dnumber2" @input="num2Input">
</div>
</template>
<script src="../js/vue.js"></script>
<script>
const app = new Vue({
el:'#app',
data(){
return{
num1:1,
num2:2
}
},
components:{
cpn:{
template:"#cpn",
props:{
number1:Number,
number2:Number
},
data(){
return{
dnumber1: this.number1,
dnumber2: this.number2
}
},
methods:{
num1Input(event){
this.dnumber1= event.target.value;
this.$emit('num1change',this.dnumber1)
},
num2Input(event){
this.dnumber2 = event.target.value;
this.$emit('num2change',this.dnumber2)
}
}
}
},
methods:{
num1change(num){
this.num1 = parseInt(num);
},
num2Change(num){
this.num2 = parseInt(num);
}
}
})
</script>
|