itsource

vuex 작업에 dayJS를 사용할 수 있지만 Vuex 저장소의 상태를 초기화할 수 없는 이유는 무엇입니까?

mycopycode 2022. 9. 11. 17:36
반응형

vuex 작업에 dayJS를 사용할 수 있지만 Vuex 저장소의 상태를 초기화할 수 없는 이유는 무엇입니까?

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({  }) {
  },
}

이 간단한 예에서는,undefined에러입니다.this인 것 같다undefined.

stateNuxt 인스턴스는 아직 정의되지 않았습니다.그리고.this"작업" (즉, Nuxt 인스턴스의 경우)bindOngepland호출되었을 때 컨텍스트가 바인딩된 일반 함수이기 때문에 동작입니다.

회피책은 컴포넌트가 상태를 초기화하는 액션을 호출하는 것입니다.유니버설 모드(또는 )에서는 스토어가 자동으로 호출되어 상태를 초기화하는 액션을 제공할 수 있습니다.

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

언급URL : https://stackoverflow.com/questions/65244446/why-can-i-use-dayjs-in-vuex-actions-but-not-to-initialize-states-in-a-vuex-store

반응형