我正在尝试使用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
。
在state
创建应用程序实例时设置is,因此尚未定义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')
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句