Answers for "Vuex get data in mounted"

0

Vuex get data in mounted

const store = new Vuex.Store({
  state: {
    globalCompanies: {
      test: null
    }
  },
  mutations: {
    setMe: (state, payload) => {
      state.globalCompanies.test = payload
    }
  },
  actions: {
    pretendFetch: ({commit}) => {
      setTimeout(() => {
        commit('setMe', 'My text is here!')
      }, 300)
    }
  }
})

new Vue({
  el: '#app',
  store,
  computed: {
    cp: function() { // computed property will be updated when async call resolves
      return this.$store.state.globalCompanies.test;
    }
  },
  watch: { // watch changes here
    cp: function(newValue, oldValue) {
      // apply your logic here, e.g. invoke your listener function
      console.log('was: ', oldValue, ' now: ', newValue)
    }
  },
  mounted() {
    this.$store.dispatch('pretendFetch');
    // console.log(this.cp, this.$store.state.globalCompanies.test); // null
    // var cn = this.$store.state.globalCompanies.test; // null
    // console.log(cn) // null
  }
})
Posted by: Guest on June-17-2021

Code answers related to "Javascript"

Browse Popular Code Answers by Language