VueJS 2:观察组件中的方法触发器

VueJS 2 : Watch method trigger in a component

我正在使用 2 个组件开发 VueJS2。

期望的行为:每次在一个组件中触发一个方法时,我想在另一个组件中触发一个方法。

我假设 watch 和 $refs 是我需要的。这是它的样子:

 watch: {
    'this.$refs.component1.method1': () => {
        console.log('TRIGGERED method1')
        this.$refs.component2.method1()
    },
    'this.$refs.component1.method2': () => {
    console.log('TRIGGERED metdod2')
    this.$refs.component2.method2()
  }

不幸的是,这不起作用。是否可以观看方法调用?

通常在这种情况下不使用观察者和引用。您可以使用什么取决于组件的组织方式。如果你想观察从 child 到 parent 的方法,你可以简单地监听组件中的自定义事件。这样您就可以使用 $emit(customevent) 从组件发出事件。然后,您可以使用 @customevent="yourMethod" 在 parent 组件中添加侦听器。

vue 文档很好地解释了这一点:

https://vuejs.org/v2/guide/components-custom-events.html

当他们没有 parent child 关系时,事件总线就是您所需要的。这通常意味着您创建一个名为 eventbus.js 的 .js 文件或包含以下内容的类似文件:

import Vue from 'vue';
export const EventBus = new Vue();

然后您可以在每个要交换事件的组件中导入您的 eventbus.js,然后像这样将事件发送到全局事件总线:

import { EventBus } from './event-bus.js';

export default {
    methods: {
        EmitmyMethod () {
            EventBus.$emit('customevent') 
        },
        ListenToMyMethod () {
            EventBus.$on('customevent')
        }
    }
}

更多信息请点击此处:

https://alligator.io/vuejs/global-event-bus/