Vuex存储正确时,组件中未定义VueJS计算值

时间:2019-10-04 15:09:36

标签: vue.js vuex

使用Vue / Vuex / Axios / Express,我试图在用户的lastAct在过去一天之内禁用按钮。我可以在商店中检索lastAct,但是我的计算值不确定。

这是我的快速路线:

// GET last act for current user
router.get('/last', auth.required, async (req, res, next) => {
  console.log(' req is: ', req);
  const lastAct = await Act
    .query()
    .where('users_id', req.user.id)
    .orderBy('created_at', 'desc')
    .limit(1);
  res.json(lastAct);
})

我的axios服务

import Api from '@/services/Api'

export default {

...

  fetchLastAct () {
    return Api().get('acts/last')
  },

  deleteAct (id) {
    return Api().delete('acts/' + id)
  }
}

这是我商店的相关部分:

import Vue from 'vue'
import Vuex from 'vuex'

...

import ActsService from './services/ActsService'

// import SubscriptionsService from './services/SubscriptionsService'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    status: '',
    user: JSON.parse(localStorage.getItem('user')),

...

  },
  mutations: {

...

    setLastAct(state, lastAct) {
      state.lastAct = lastAct;
      console.log('store sets this last act: ', lastAct) // returns correct object
    }
  },
  actions: {

...

    async getLastAct({ commit }) {
      await ActsService.fetchLastAct()
        .then(resp => {
          console.log('this is the last act: ', resp); // returns correct object
          commit('setLastAct', resp.data[0]);
        });
    }
  },
  getters: {

    ...

    lastAct: state => {
      return state.lastAct;
    }
  }
})

和我组件的计算值:

  computed: {
    ...,
    actedToday() {
      // const now = new Date();
      console.log('this is computed last act', this.$store.state.lastAct) //returns undefined
      return this.$store.state.lastAct
      // .created_at > now.setHours(0,0,0,0)
    }
  }

2 个答案:

答案 0 :(得分:0)

lastAct属性添加到您的初始状态。 Vue赢得了动态属性跟踪,请参见this

答案 1 :(得分:0)

这里有一个example,可以帮助您了解商店的工作方式。