我有一个函数,它将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);
})
}
}
})