Correcting teacher:PHPz
Correction status:qualified
Teacher's comments:
父组件App.vue
<template>
<fieldset>
<legend>组件间通信</legend>
<!-- 使用父组件 Children.vue -->
<!-- 向子组件传值num 并接收Children.vue文件传来的值-->
<Children :num="num" @app_edit="app_edit"></Children>
这是子组件Children.vue传给父组件App.vue的值: {{ num }}
</fieldset>
</template>
<script>
// 引入父组件 Parent.vue
import Children from "./components/Children";
export default {
// 引入组件后 要在此注册
components: {
Children,
},
data() {
return {
num: 0,
};
},
methods: {
app_edit(e) {
console.log("我是父文件的app_edit方法");
// console.log(e);
this.num = e;
},
},
};
</script>
子组件Parent.vue
<template>
<div class="">
<h1>{{ msg }}</h1>
接受App.vue文件传过来的值为: {{num}} <hr>
<button @click="add_num"> 每次+1</button>
<button @click="cut_num"> 每次-1</button>
</div>
</template>
<script>
export default {
data() {
return {
msg: "这是子组件",
};
},
props:['num'],
methods: {
add_num(){
// console.log(this.num);
console.log("Parent.vue文件下的add_num方法");
// 将传过来的值+1处理传回App.vue
this.$emit('app_edit',this.num+1);
},
cut_num(){
// console.log(this.num);
console.log("Parent.vue文件下的cut_num方法");
// 将传过来的值+1处理传回App.vue
this.$emit('app_edit',this.num-1);
}
},
};
</script>
最终效果
更多组件通信及生命周期参考:http://www.ouyangke.com/front/vue3/3Vue3%E7%BB%84%E4%BB%B6.html