【问题标题】:Vuex mapState based on route and route parametersVuex mapState 基于路由和路由参数
【发布时间】:2021-02-23 16:00:40
【问题描述】:

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

在我的 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)
                })
        },
    },
})

【问题讨论】:

    标签: vue.js vuex


    【解决方案1】:

    你可以在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

    更新:

    要通过路由更改来更新映射属性,您必须强制重新渲染组件。最好的办法是在父组件路由改变时改变组件键。

    父.vue

    <template>
      <categoryComponent :key="key"></categoryComponent> // <-- This is the component you work with
    </template>
    
    computed: {
      key(){
         return this.$route.params.category
      }
    }
    

    使用这种方法,每次路由更改都会触发beforeCreate 挂钩,从 Vuex 获取新数据。

    【讨论】:

    • 我试过了,但是状态返回 undefined
    • 感谢您的回答。它在创建时看起来有效,但在路由更改时无效。我对所有类别都使用了一个作品组件。
    • 路由改变时必须触发beforeCreate钩子。我已经更新了我的答案怎么做。
    • 非常感谢!你认为这是我正在做的坏方法吗?
    • 我不认为这很糟糕。在某些情况下,这是一种有效的方法。当这是唯一的选择时,我自己做了。干杯!
    猜你喜欢
    • 1970-01-01
    • 2016-03-05
    • 1970-01-01
    • 1970-01-01
    • 2017-06-14
    • 2017-12-03
    • 1970-01-01
    • 2017-01-24
    • 2023-03-23
    相关资源
    最近更新 更多