<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div id="app">
<cpn
:cnum1="num1"
:cnum2="num2"
@num1change="num1change"
@num2change="num2change"
></cpn>
</div>
<!-- 子模板 -->
<template id="cpn">
<div>
<h2>porps:{{cnum1}}</h2>
<h2>data:{{dnum1}}</h2>
<!-- <input type="text" v-model="dnum1" /> -->
<!-- v-model原理 -->
<input type="text" :value="dnum1" @input="num1Input" />
<h2>porps:{{cnum2}}</h2>
<h2>data:{{dnum2}}</h2>
<!-- v-model原理 -->
<!-- <input type="text" v-model="dnum2" /> -->
<input type="text" :value="dnum2" @input="num2Input" />
</div>
</template>
<script src="../vue.js"></script>
<script>
const app = new Vue({
el: "#app",
data: {
num1: 1,
num2: 0,
},
methods: {
num1change(value) {
this.num1 = parseInt(value);
},
num2change(value) {
this.num2 = parseInt(value);
},
},
// 子组件
components: {
cpn: {
template: "#cpn",
props: {
cnum1: Number,
cnum2: Number,
},
data() {
return {
dnum1: this.cnum1,
dnum2: this.cnum2,
};
},
methods: {
num1Input(event) {
// 将input中的value赋值到dnum1中
this.dnum1 = event.target.value;
// 为了让父组件可以修改值,发出一个事件
this.$emit("num1change", this.dnum1);
//同时修饰dnum2的值,然后把dnum2的值再次发送出去
this.dnum2 = this.dnum1 * 100;
this.$emit("num2change", this.dnum2);
},
num2Input(event) {
this.dnum2 = event.target.value;
this.$emit("num2change", this.dnum2);
this.dnum1 = this.dnum2 / 100;
this.$emit("num1change", this.dnum1);
},
},
},
},
});
</script>
</body>
</html>
Vue学习案例:父子通信-结合双向绑定案例
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。