programing

Vuex - 바인딩 도우미의 동적 네임스페이스(mapState, ...)

nicescript 2022. 7. 14. 21:29
반응형

Vuex - 바인딩 도우미의 동적 네임스페이스(mapState, ...)

vuex 스토어 모듈을 동적으로 등록하고 있습니다.

store.registerModule('home.grid', GridStore)

다음 컴포넌트에서 다음을 수행합니다.

export default {
name: 'GridComponent',

props: {
  namespace: {
    type: String,
    required: true
  },

 computed: {
    ...mapState(this.namespace, ['filter']) // doesn't work
    filter() { // more verbose but working
      return this.$store.state[this.namespace].filter
    }
 }
 ...

그런데 에러가 났어요.

정의되지 않은 속성 'namespace'를 읽을 수 없습니다.

감 잡히는 게 없어요?

https://forum.vuejs.org/t/vuex-dynamic-namespaces-in-mapstate-mapactions/28508의 "httpaum10"에서 질문한 내용입니다.

여기에서 해결 https://github.com/vuejs/vuex/issues/863#issuecomment-329510765

{
  props: ['namespace'],

  computed: mapState({
    state (state) {
      return state[this.namespace]
    },
    someGetter (state, getters) {
      return getters[this.namespace + '/someGetter']
    }
  }),

  methods: {
    ...mapActions({
      someAction (dispatch, payload) {
        return dispatch(this.namespace + '/someAction', payload)
      }
    }),
    ...mapMutations({
      someMutation (commit, payload) {
        return commit(this.namespace + '/someMutation', payload)
      })
    })
  }
}

이를 위한 다른 접근법은 계산된 속성이 데이터 속성 이후에 초기화된다는 사실을 이용하는 것일 수 있다.이 방법은 데이터보다 먼저 메서드가 계산되므로 계산된 속성에서만 작동합니다.

예:

export default {
  props: {
    namespace: {
      type: String,
      required: true
    },
  },
  data(){
    // Append more computed properties before they are initialized.
    this.$options.computed = {
      ...this.$options.computed,
      ...mapState(this.namespace, ['filter'])
    }

    return {
      foo: bar
    }
  },

}

동적 getter를 만들 때도 기본적으로 동일한 문제가 발생하지만 어떤 이유로 구성 요소의 데이터 변수를 사용하여 vuex 맵 기능을 수행할 수 없습니다.

그래서 이건 나한테 안 통했어

 ...mapGetters( this.layout,['getFilterByObject'])

하지만 난 할 수 있어

this.$store.getters[this.layout + '/getFilterByObject'](filterGroup)

아마 당신은 당신의 주(州)와 비슷한 것을 할 수 있을 것이다, 하지만 나는 그것을 테스트하지 않았다.

this.$store.state[this.namespace].filter

언급URL : https://stackoverflow.com/questions/55927452/vuex-dynamic-namespaces-in-binding-helpers-mapstate

반응형