当我的Vuex Getter在观察者中返回空值时,如何从状态中获取值

时间:2019-01-31 11:10:57

标签: vue.js vuejs2 vuex vuex-modules

吸气剂被返回在观察者空值。但状态被适当地设定在突变。

无法在控制台中检入Vuex开发工具,因为它显示“未检测到存储”。我已经通过在控制台中登录对其进行了检查

Vue的文件:


computed: {
    ...mapGetters('listings', ['listingContracts']),
},

methods: {
    ...mapActions('listings', [
      'productBasedListings',
    ]),
},

onChange(product) {
      this.productBasedListings( product.id );
      console.log('LIST:', this.listingContracts); // Empty in observer
},

商店:


state: {
    contracts: [],
},

getters: {
    listingContracts(state) {
      console.log('GETTER', state.contracts); // Empty in observer
      return state.contracts;
    },
},

mutations: {
    setListing(state, { lists }) {
      state.contracts = lists;
      console.log('AFTER MUTATION:', state.contracts); // Setting the value properly
    },
},

actions: {
    async productBasedListings({ commit }, { id, state }) {
      let listing = [];
      try {
        listing = await publicApi.listings(id);
        console.log('ACTION:', listing);

        commit({
          lists: listing,
          type: 'setListing',
        });
      } catch (e) {
        console.error(`Failed to change  #${id} state to  #${state}:\t`, e);

        throw e;
      }
    },
}

下面“吸气剂”不具有任何值,但“突变后”,我们具有的值。

enter image description here

1 个答案:

答案 0 :(得分:0)

因为最初存储变量为空,值本身是在突变中设置的,因此在调用突变后会显示出来。

现在,要在触发突变后获取数据,请在您的方法中使用async等待,如下所示:

async onChange(product) {
      await this.productBasedListings( product.id ).then(() => {
      console.log('LIST:', this.listingContracts); 
      })
},
相关问题