vue subassemblies, call the parent component There are three ways Ha! Let's work together to explain.
The first use of this. $ Parent. The parent components by direct methods in the subassembly. Method calls the parent component
first disadvantage is not able to pass parameters ha. You can only call methods.
子组件.vue
<template>
<div @click="fa">
我是子组件
</div>
</template>
<script>
export default {
methods:{
fa(){
// 第一种 直接在子组件中通过this.$parent.父组件中的方法 来调用父组件的方法
this.$parent.fatherMethod('op');//父组件中有这一个方法fatherMethod
}
}
}
</script>
父组件.vue
methods:{
fatherMethod(){
console.log("被子组件触发了")
}
}
The second
The method is triggered in the sub-components in the parent component with $ emit an event, parent component listens to this event on the line can pass parameters
The third
子组件.vue
<template>
<div @click="mychild()">
我是子组件
</div>
</template>
<script>
export default {
props: {
say: {
type: Function,
default: null
}
},
methods:{
// 第三种是父组件把方法传入子组件中,在子组件里直接调用这个方法
mychild(){
if (this.say) {
this.say();
}
}
}
}
</script>
父组件
<zidiaoyongfa :say="say"></zidiaoyongfa>
say(){
console.log("haha 我要说话")
}