Search code examples
vue.jsvuex

How to change state in one component and listen to it in another Vue.js?


I have two components. In one of the I'm commiting change to the store on click. In another I want to listen to this change and react to it.

If I look at my Vuex store my commit is working on every click but I'm not sure how to listen for it in another component.

Component A

methods: {
        openMenu() {
            this.open = !this.open;
            this.$store.commit('OPEN_MENU', this.open);
        }
    }

<button @click="openMenu"></button>

In my Component B I tried binding to computed property but it only runs once, when component is created.


Solution

    1. Create vuex getter for 'open'
    2. Create the computed property in component B:
    computed: {
      open () {
        return this.$store.getters.open
      }
    }
    
    1. Use this.open in script or template