state - 为什么我可以在 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
.
解决方案
这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')
}
}
推荐阅读
- java - Android中没有预期的输出
- javascript - 点击事件不适用于仅使用 Javascript 的轮播
- docker - Hortonworks HDP docker如何公开端口
- typescript - Typescript 中的动态键
- python - 无法从外部应用程序发送 JSON,但我的 Django 测试有效
- python - 删除 XML 声明标记的 Python 代码
- asp.net - Razor 和 MVC 页面的 Asp.net Core 应用程序问题
- c - 相同的 C 程序但不同的执行时间
- ios - XCode 调试器不会显示所有变量内容。它是一个错误吗?
- postgresql - 在更新我们读取的行时从 Postgres 只读副本进行缓慢的批量读取