首页 > 解决方案 > 为什么我可以在 vuex 操作中使用 dayJS,但不能在 Vuex 存储中初始化状态?

问题描述

我正在尝试使用 NuxtJSdayjs模块将初始月份设置为当前月份。

为什么我可以this.$dayjs在动作中使用但不能在状态中使用?它不应该是全球可访问的吗?

我怎样才能在状态中初始化当前月份?

export const state = () => ({
  month: this.$dayjs().startOf('month'), //THIS LINE DOESNT WORK
})
export const mutations = { }
export const actions = {
  bindOngepland: firestoreAction(function ({ bindFirestoreRef, rootState }) {
    const month = this.$dayjs().startOf('month') // THIS LINE DOES WORK
    const nextMonth = state.month.add(1, 'month')
  }),
  setNextMonth({  }) {
  },
}

在这个简化的示例中,我收到undefined第 2 行的错误。this似乎是undefined.

标签: statenuxt.jsvuexdayjs

解决方案


state是在创建应用程序实例时设置的,因此尚未定义 Nuxt 实例。并且在操作this中“工作”(即,是您的 Nuxt 实例),bindOngepland因为它是一个常规函数,在被调用时具有其上下文绑定。

一种解决方法是让组件调用初始化状态的操作。在通用模式(或ssr: true)下,商店可以提供一个自动调用来初始化状态的nuxtServerInit操作

// store/index.js
export const actions = {
  nuxtServerInit({ commit }) {
    commit('SET_MONTH', this.$dayjs().startOf('month'))
  }
}

export const mutations = {
  SET_MONTH(state, value) {
    state.month = value
  }
}

在 SPA 模式 ( ssr: false) 中,您必须明确调度操作:

// store/index.js
export const actions = {
  init({ commit }) {
    commit('SET_MONTH', this.$dayjs().startOf('month'))
  }
}

export const mutations = {
  SET_MONTH(state, value) {
    state.month = value
  }
}

// MyComponent.vue
export default {
  mounted() {
    this.$store.dispatch('init')
  }
}

推荐阅读