Vuex mapState 基于路由和路由参数

Vuex mapState based on route and route parameters

我有一个工作组件,我在我的应用程序上使用了不同的页面,我正在尝试根据路由和路由参数加载状态。

在我的 App.vue 文件中,我调度异步操作以获取 json 文件,如

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

然后我将状态映射到我的工作组件中

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

我实际上需要根据路由动态映射状态,就像 state.works[this.$router.currentRoute.params.category] 或基于路由名称一样。 你能告诉我从我的状态获取数据(异步)的正确方法是什么吗?

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

更新:

要使映射属性随着路由更改而更新,您将必须强制重新渲染组件。最好的方法是在父组件中的路由更改时更改组件键。

Parent.vue

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

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

使用这种方法,beforeCreate 钩子将在每次路由更改时触发,从 Vuex 获取新数据。