在VUE 中,如何实现子组件调用父组件中的方法?
首先,在父组件中引入子组件,并注册组件:
引入组件:
import Ma60CardsGatherPage from '../9_maintenenceOutline/MA60/MA60CardsGatherPage.vue'
注册组件:
export default {
components:{
Num1Page:Ma60CardsGatherPage,
},
}
在父组件中使用子组件:
<!-- 子组件调用父组件中的方法,要在组件中进行绑定,方法名应该小写,父子组件方法保持一致避免问题 -->
<Num1Page v-on:add1="add1" @add2="add2" @add3="add3" @add4="add4"></Num1Page>
这里要注意的是,子组件中的方法通过v-on绑定父组件中的方法,格式为:
v-on: childmethod="parentmethod’
需要注意的是:
- 方法名如果使用驼峰命名法,在调用时可能会无效,建议保持全小写。
- 父子组件方法名可以不一样,但为了避免出错,尽量保持一致。
- 子组件可以绑定多个方法。
核心代码:
这是子组件中的方法:
add1(){
console.log("子组件add1");
this.$emit("add1");
},
如果包含参数,通用格式为:
add1(params){
console.log("子组件add1");
this.$emit("fathermethod",params);
},
父组件中的方法:
add1(params) {
console.log("this is fathermethod.")
},