不积跬步,无以至千里;不积小流,无以成江海。
Vuejs语言基础
父子组件通信——子传父:
通过 this.$emit 提交一个事件,将子组件的行为或者数据告诉父组件
- 修改父组件的值
1. 创建一个子组件 Child.vue
<template>
<div class="my-child">
<h5>我是子组件,我可以通过属性props来接收父组件传过来的年龄值是:{{deliverParentAge}},这是一个数字类型</h5>
<h5>并且,我要告诉他,他今年生日已经过了,所以他的年龄应该<button @click="AddAge">加1</button></h5>
</div>
</template>
<script>
export default {
data() {
return {
childAge: 27
};
},
props: {
deliverParentAge: Number
},
// 新建一个计算属性,将父组件原来的值加1
computed: {
parentActualAge() {
return this.deliverParentAge + 1;
}
},
methods: {
AddAge() {
this.$emit("addParentAge", this.parentActualAge);
}
}
};
</script>
2. 创建父组件,通过 v-on 来监听子组件提交的事件 addParentAge;
addParentAge是子组件提交的事件名称,也是父组件通过v-on监听的事件名称,而handleAddParentAge是父组件自定义的方法名称
<template>
<div class="my-parent">
<h3>我是父组件,我想告诉我的子组件,我的年龄值是:{{parentAge}}</h3>
<h3>我要通过v-bind绑定一个属性parentAge,告诉子组件我的年龄值是:{{parentAge}}</h3>
<!-- 下面就是我的子组件 -->
<my-child :deliverParentAge="parentAge"
@addParentAge="handleAddParentAge"></my-child>
</div>
</template>
<script>
import MyChild from "./Child";
export default {
components: { MyChild },
data() {
return {
parentAge: 49
};
},
methods: {
handleAddParentAge(actualAge) {
console.log("父组件的实际年龄是:", actualAge);
}
}
};
</script>
- 将子组件data中的值,提交给父组件
1. 创建子组件 Child.vue
<template>
<div class="my-child">
<h5>我是子组件,我可以通过属性props来接收父组件传过来的年龄值是:{{deliverParentAge}},这是一个数字类型</h5>
<h5>现在我要告诉父组件,我的年龄是{{childAge}}</h5>
</div>
</template>
<script>
export default {
data() {
return {
childAge: 27
};
},
props: {
deliverParentAge: Number
},
methods: {
DiffAge() {
this.$emit("differAge", this.childAge);
}
}
};
</script>
2. 父组件通过 v-on 监听子组件提交的事件 differAge
<template>
<div class="my-parent">
<h3>我是父组件,我想告诉我的子组件,我的年龄值是:{{parentAge}}</h3>
<!-- 下面就是我的子组件 -->
<my-child :deliverParentAge="parentAge"
@differAge="handleDifferAge"></my-child>
<h3>通过监听子组件提交的事件addParentAge,我知道到了自己的实际年龄应该是:
</div>
</template>
<script>
import MyChild from "./Child";
export default {
components: { MyChild },
data() {
return {
parentAge: 49
};
},
methods: {
handleDifferAge(child) {
console.log("子组件年龄是:", child);
}
}
};
</script>
浙公网安备 33010602011771号