代码之家  ›  专栏  ›  技术社区  ›  Onyx

我应该把两个或更多人使用的函数放在哪里虚拟用户.js组件?

  •  0
  • Onyx  · 技术社区  · 5 年前

    我有一个函数,它将ID作为参数,并从存储在Vuex存储区中的JSON中查找该ID所属的对象。到目前为止,我只在1个组件中使用了这个函数,但是,我最近创建了第二个组件,它也需要这个函数。目前我刚刚复制和粘贴的功能,但是,这似乎不是最佳的。这就是为什么我想知道应该把这个函数放在哪里,这样所有需要它的组件都可以访问它。

    我一直在想Vuex商店是否是一个可行的存储功能的地方,但我不太确定,所以我决定征求您的意见。谢谢

    findChampionName(id){
        let championId = id.toString();
        let champion = Object.entries(this.$store.state.champions).find(([key,value]) => value.key === championId);
    
        return champion[1]
    }
    

    Vuex商店:

    export default new Vuex.Store({
        state: {
            champions: null
        },
        mutations: {
            champions(state, data){
                state.champions = data.champions
            }
        },
        actions: {
            getChampions({commit, state}){
                axios.get("https://ddragon.leagueoflegends.com/cdn/9.14.1/data/en_US/champion.json")
                .then((response) => {
                    commit('champions', {
                        champions: response.data.data
                    })
                })
                .catch(function (error) {
                    console.log(error);
                })
            }
        }
    })
    
    1 回复  |  直到 5 年前
        1
  •  1
  •   Roland    5 年前

    据我所知,您应该使用vuex getter处理您的案例:

    getters: {
        getChampionName => state => id => {
            let championId = id.toString();
            let champion = Object.entries(state.champions).find(([key,value]) => value.key === championId);
    
            return champion[1]
        }
    }
    

    您可以通过传递id来访问该getter: this.$store.getters['findChampionName'](id)