需求:
1.父组件data中有两个属性num1=0,num2=1
2.将这两个属性的值传到子组件中,子组件的props中有两个属性number1,number2分别接收这两个值,作为初始化值显示在屏幕上
3.子组件模板中有个input输入框,现在,我在输入框中输入值,希望能传到一个变量里面,这里注意,用v-model去双向绑定的时候,不能绑定props里面的number1,number2,只能绑定data里面的东西,所以在data中定义两个变量dnumber1和dnumber2,我们可以把在input框中输入的值传到这两个变量里面
4.现在我还想把输入框中的值通过emit一个事件传到父组件,从而修改父组件data中的num1和num2的值
实现1
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Title</title>
</head>
<body>
<div id="app">
<cpn :number1="num1" :number2="num2" @num1change="num1C" @num2change="num2C"></cpn>
</div>
<template id="cpn">
<div>
<h2>props里的:{{number1}}</h2>
<h2>data里的:{{dnumber1}}</h2>
<input type="text" :value="dnumber1" @input="num1Input">
<h2>props里的:{{number2}}</h2>
<h2>data里的:{{dnumber2}}</h2>
<input type="text" :value="dnumber2" @input="num2Input">
</div>
</template>
<script src="../js/vue.js"></script>
<script>
const app = new Vue({
el:'#app',
data:{
num1: 0,
num2: 1,
},
methods: {
num1C(value){
this.num1=parseInt(value);
},
num2C(value){
this.num2=parseInt(value);
}
},
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)
},
}
}
}
})
</script>
</body>
</html>
实现2(用到v-model和watch选项)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Title</title>
</head>
<body>
<div id="app">
<cpn :number1="num1" :number2="num2" @num1change="num1C" @num2change="num2C"></cpn>
</div>
<template id="cpn">
<div>
<h2>props里的:{{number1}}</h2>
<h2>data里的:{{dnumber1}}</h2>
<input type="text" v-model="dnumber1"><br>
<h2>props里的:{{number2}}</h2>
<h2>data里的:{{dnumber2}}</h2>
<input type="text" v-model="dnumber2"><br>
</div>
</template>
<script src="../js/vue.js"></script>
<script>
const app = new Vue({
el:'#app',
data:{
num1: 0,
num2: 1,
},
methods: {
num1C(value){
this.num1=parseInt(value);
},
num2C(value){
this.num2=parseInt(value);
}
},
components: {
cpn: {
template: `#cpn`,
props: {
number1: Number,
number2: Number,
},
data(){
return {
dnumber1: this.number1,
dnumber2: this.number2,
}
},
watch: {
dnumber1(newValue){
this.dnumber1 = newValue;
this.$emit('num1change',newValue)
},
dnumber2(newValue){
this.dnumber2 = newValue;
this.$emit('num2change',newValue)
},
}
}
}
})
</script>
</body>
</html>