<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>组件通信</title>
</head>
<body>
<div id="app">
<children-cpn
:number1="num1"
:number2="num2"
@num1change="num1change"
@num2change="num2change"
></children-cpn>
</div>
<template id="childrenCpn">
<div>
<h2>props:{{number1}}</h2>
<h2>data:{{dnumber1}}</h2>
<!--如果要修改数据的话避免直接绑定到 number1 这个数组对象上-->
<!--需要修改就绑定到子组件的 data 里数据对象上-->
<!--<input type="text" v-model="dnumber1">-->
<!--<input type="text" v-bind:value="dnumber1" @input="dnumber1=$event.target.value">-->
<input type="text" v-bind:value="dnumber1" @input="num1Input">
<h2>props:{{number2}}</h2>
<h2>data:{{dnumber2}}</h2>
<!--<input type="text" v-model="dnumber2">-->
<!--这个($event) 可以省略不写 -->
<input type="text" v-bind:value="dnumber2" @input="num2Input($event)">
</div>
</template>
<script src="../js/vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
num1: 1,
num2: 2
},
methods: {
num1change(value) {
// 查看参数类型,因为是从输入框获取,默认为string类型数据
console.log(typeof value);
this.num1 = parseInt(value);
},
num2change(value) {
this.num2 = parseInt(value);
}
},
components: {
childrenCpn: {
template: '#childrenCpn',
props: {
// 要求参数必须为 number 类型
number1: Number,
number2: Number
},
data() {
return {
dnumber1: this.number1,
dnumber2: this.number2
}
},
methods: {
num1Input(e) {
this.dnumber1 = e.target.value;
this.$emit('num1change', this.dnumber1)
},
num2Input(e) {
this.dnumber2 = e.target.value;
this.$emit('num2change', this.dnumber1)
}
}
}
}
})
</script>
</body>
</html>
其中这个
?@input="num2Input($event)"
是可以被 子组件中的?watch()替代的,watch 方法可以监听某个属性是否发生变化,一旦发生某个变化,就会触发这个监听机制;
|