为什么我可以在 vuex 操作中使用 dayJS 但不能在 Vuex 存储中初始化状态?

Why can I use dayJS in vuex actions but not to initialize states in a Vuex store?

我正在尝试使用 NuxtJS dayjs 模块将初始月份设置为状态中的当前月份。

为什么我可以在动作中使用 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({  }) {
  },
}

在这个简化的示例中,第 2 行出现 undefined 错误。this 似乎是 undefined

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

解决方法是让组件调用初始化状态的操作。在通用模式下(或自动调用初始化状态的ssr: true), the store can provide a nuxtServerInit action

// 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')
  }
}