3

I'm working on VueJS2 with 2 components.

Desired behaviour: Each time a method is triggered in one component, i would like to trigger a method in the other component.

I assume watch and $refs are what I need. this is what it looks like :

 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()
  }

Unfortunately, this doesn't work. Is it possible to watch a method call?

1 Answer 1

1

Typically watchers and refs are not used in this scenario. What you can use depends a bit how the components are organized. If you want to watch a method from child to parent you can simply listen to a custom event in the component. That way you would emit the event from the component using $emit(customevent). You can then add the listener in the parent component using @customevent="yourMethod".

The vue docs explain that very nicely:

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

When they do not have a parent child relationship the event bus is what you need. This typically means that you create a .js file called eventbus.js or something like that containing this:

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

You can then import your eventbus.js in every component where you want to exchange events and then emit events to the global evenbus like this:

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

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

More info about that here:

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks a lot for your answer, I have another question then, is it be possible to watch for data change in a component using refs? Could you tell me if something like this would work? watch: { 'this.$refs.component1.dataFromComponent1': () => { console.log('Data modified!') } }
After trying, it doesnt seem to work. Not sure if i'm using it the right way though
Watchers are part of the Vue framework but very seldom needed. Watchers do not work across components. Passing information between components should always happen via props or events. With the simplest form being props/events, a more complicated form the eventbus and the most complex form by implementing Vuex.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.