IT이야기

Vuex mapState 경로와 경로 매개 변수에 근거한다.

cyworld 2022. 5. 17. 21:58
반응형

Vuex mapState 경로와 경로 매개 변수에 근거한다.

나는 내가 길, 경로 매개 변수에 기초를 둔 상태를 로드하려고 노력하고 있습니다 나는 앱에 다른 페이지 사용하는 작품 요소를 가지고 있습니다.

내 App.vue 파일은 내가async 조치처럼json 파일을 발송 가능하다.

mounted() {
    this.$store.dispatch('getData')
},

And I map the state in my works component like that

export default {
    name: 'Works',
    computed: mapState({
        works: (state) => state.works.home.items.slice(0, state.works.home.loadedCount),
        loadedCount: (state) => state.works.home.loadedCount,
        totalCount: (state) => state.works.home.items.length,
    })
}

사실 나는 동적으로 상태처럼 도중에 기초를 둔 상태를 파악할 필요가 있다.이[ 일한다.달러router.currentRoute.params.category 해결 혹은 경로 이름을 기준으로.제가 어떻게 올바른 방식으로 우리 주에서 데이터를(async)을 얻는 것이다 말씀해 주시겠습니까?

Vuex점:

export default new Vuex.Store({
    state: {
        works: {
            all: {
                items: [],
                loadedCount: 0,
            },
            home: {
                items: [],
                loadedCount: 0,
            },
            web: {
                items: [],
                loadedCount: 0,
            },
            print: {
                items: [],
                loadedCount: 0,
            },
        },
        limit: 2,
    },
    mutations: {
        SET_WORKS(state, works) {
            state.works.all.items = works
            works.map((el) => {
                if (typeof state.works[el.category] !== 'undefined') {
                    state.works[el.category].items.push(el)
                }
            })
        },
    },
    actions: {
        getData({ commit }) {
            axios
                .get('/works.json')
                .then((response) => {
                    commit('SET_WORKS', response.data.works)
                })
        },
    },
})

여러분은 할 수 있다.beforeCreate낚다

beforeCreate(){
    const category = this.$route.params.category;

    Object.assign(this.$options.computed, {
      ...mapState({
        categoryItems: (state) => state.categories[category],
      }),
    });
}

나는 기본적인 노동 예:https://codepen.io/bgtor/pen/OJbOxKo?editors=1111.를 만들었습니다.

업데이트:

매핑 된 속성 경로 변화와 함께 업데이트되려면 각 re-render한테 강제로 시킬 것이다.가장 좋은 방법은 그것을 할, 부모 구성 요소에서 노선 변화는 구성 요소의 키를 바꾸는 것이다.

Parent.vue

<template>
  <categoryComponent :key="key"></categoryComponent> // <-- This is the component you work with
</template>

computed: {
  key(){
     return this.$route.params.category
  }
}

이 다가옴에 따라서,beforeCreate훅 모든 경로 변화로 Vuex에서 신선한 데이터고 촉발될 것이다.

참조URL:https://stackoverflow.com/questions/66336643/vuex-mapstate-based-on-route-and-route-parameters

반응형