📜  Vuex 在挂载中获取数据 - Javascript 代码示例

📅  最后修改于: 2022-03-11 15:04:15.503000             🧑  作者: Mango

代码示例1
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
  }
})