关于vue.js:从子组件中调用父函数的父函数

Call a parent of parent function from child component

我在ChildComponent中有一个simpleMethod函数,可调用父组件的函数,但我有下一种情况:

ViewComponent扩展了LayoutComponent并在子组件内部。像这样的东西:

ChildComponent:

1
2
3
4
5
6
7
8
9
10
<template>
  <button @click="simpleMethod">smth</button>
</template>

...
methods: {
  simpleMethod() {
    this.$parent.parentFunction()
  }
}

ViewComponent:

1
2
3
4
5
6
7
8
9
10
11
12
<template>
  <onepage-layout>
    <child-component></child-component>
  </onepage-layout>
</template>

...
methods: {
  parentFunction() {
    console.log('I want to fire this function...')
  }
}

因此,当子组件触发simpleMethod函数时,它将在OnePageLayout组件中代替ViewComponent来搜索该函数。

我认为我可以像在子组件中那样在OnePageLayout中创建一个parentFunction,但是我认为这没有效果或不是一种好习惯。

有什么主意吗?


子组件:

1
2
3
4
5
6
7
8
9
10
<template>
  <button @click="simpleMethod">smth</button>
</template>

...
methods: {
  simpleMethod() {
    this.$emit('callParentFunction'); // emit an event to parent
  }
}

ViewComponent:

1
2
3
4
5
6
7
8
9
10
11
12
<template>
  <onepage-layout>
    <child-component @callParentFunction="parentFunction"></child-component>
  </onepage-layout>
</template>

...
methods: {
  parentFunction() {
    console.log('I want to fire this function...')
  }
}

您可以参考我的另一个答案。

The communication between parent and child should be using Props down events up, instead of directly call the function thru this.$parent.function(). You should $emit('callFunc') then @callFunc="function".


实现此目标的好方法是使用新的vue实例作为事件总线:

window.EventBus =新的Vue();

在子组件中,您可以运行childFunction

1
2
3
4
5
6
7
 methods: {

        childFunction() {
            EventBus.$emit('call-parent-function')
        }

    }

然后在任何组件(如parent的parent!)中,您都可以收听以下事件:

1
2
3
4
5
6
7
 created() {          

        EventBus.$on('call-parent-function', () => {
            this.parentFunction();
        })

    }