VueJS 计算值在组件中未定义,而 Vuex 存储是正确的

VueJS computed value undefined in component while Vuex store is correct

使用 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)
    }
  }

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

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