Data variable not updated from observer on computed property in Vue.js with Vuex

Fiddle: https://jsfiddle.net/mjvu6bn7/

I have an observer on a computed property that has a dependency on a Vuex storage variable that is set asynchronously. I am trying to set a Vue component data variable when this computed property changes, but this does not happen.

Here is the Vue component:

new Vue({
  el: '#app',
  store,
  data : {
        myVar : ""

  },
  beforeMount() {
        this.$store.dispatch('FETCH_PETS', {
        }).then(() => {
                    console.log("fetched pets")
        })

  },
  computed:{
      pets(){
        return this.$store.state.pets
      }
    },
  watch:{
    pets: (pets) => {
      console.log("Inside watcher")
      this.myVar = "Hey"
    }
  }
});

Here is the Vuex repository:

const state = {
  pets: []
};

const mutations = {
  SET_PETS (state, response) {
        console.log("SET_PETS")
    state.pets = response;
  }
};

const actions = {
 FETCH_PETS: (state) => {
      setTimeout(function() { 
            state.commit('SET_PETS', ['t7m12qbvb/apple_9', '6pat9znxz/1448127928_kiwi'])
    }, 1000)
 }
}

const store = new Vuex.Store({
  state,
  mutations,
  actions
});

A script has been created here for this. As you can see, myVar is not updated, however, the observer receives a call when pets are loading.

+4
source share
2 answers

, ES6 arrow this ( - function). , this pets window myVar Vue . , :

watch: {
    pets(pets) {
        console.log("Inside watcher")
        this.myVar = "Hey"
    }
}
+4

, , .

:

watch:{
    var that = this;
    pets: (pets) => {
      console.log("Inside watcher")
      that.myVar = "Hey"
    }
+1

Source: https://habr.com/ru/post/1660481/


All Articles