我有一个函数,它接受一个 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);
})
}
}
})
据我所知,您应该为您的案例使用 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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句