【问题标题】:Why can I use dayJS in vuex actions but not to initialize states in a Vuex store?为什么我可以在 vuex 操作中使用 dayJS,但不能在 Vuex 存储中初始化状态?
【发布时间】:2021-03-22 11:04:42
【问题描述】:

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

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

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

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.js vuex dayjs


    【解决方案1】:

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

    解决方法是让组件调用初始化状态的操作。在通用模式(或ssr: true)下,store 可以提供一个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')
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-11-24
      • 1970-01-01
      • 2019-10-30
      • 1970-01-01
      • 2018-06-30
      • 1970-01-01
      • 2020-06-27
      • 2021-09-16
      • 2020-03-08
      相关资源
      最近更新 更多