0

I have 2 vue files here. header.vue and sidebar.vue. Both the components are imported in layout.vue.

Steps

1 I'am updating the store in header.vue initially when page loads with some values inside the created hook.

2 I do a specific thing in sidebar.vue that is related to store which needs to be done once the store has the particular value ( ppglink - which only comes when store gets updated from header )

Sidebar.vue:

<li class="nav-item">
  <a class="nav-link" :href="ppgLink" target="_blank">
   ppglink
 </a>
</li>

mounted() {
 this.ppgLink = this.$store.state.website.ppglink;
}

ppgLink can be any link ( eg - www.google.com )

ppgLink gets its value while store is being updated in the created() of the header.vue. Sometimes ppgLink gets its value correctly, ( the case maybe when mounted of sidebar only executes after created() has finished ) . But in other cases it would be - undefined.

Is there a way to watch store using watcher:, just as we watch other variables in vue file, and update the ppg link once the store has some change . Or can anyone suggest a correct method , so that ppglink always get its value, maybe some lines of code in sidebar.vue should get executed once the ppglink is updated in header.

Went through many answers in this SO Question - vue.js 2 how to watch store values from vuex But Its a bit old I guess , did not get the correct solution. Can anybody point me the right way

theFrontEndDev
  • 890
  • 1
  • 17
  • 41
  • 1
    Could you add the code of your Vuex store? Also please provide all the relevant code in Header.vue and Sidebar.vue. Btw, I would suggest that you follow the best practices and use `mapState` to map the `ppgLink` state to a computed property and then watch it as explained in the link you provided. Also why do you say you didn't get the correct solution? It should work fine if properly implemented. – sebasaenz Jul 28 '20 at 14:05

1 Answers1

2

Is there a way to watch store using watcher:, just as we watch other variables in vue file

Yes, you can watch variables from your state in a Vue component like so:

import { mapState } from "vuex";

export default {
  computed: {
    ...mapState(["myField"])
  },
  watch: {
    myField(newVal) {
      console.log(newVal);
    }
  }
}
Gaetan C.
  • 1,742
  • 13
  • 21