【发布时间】:2020-04-16 19:25:47
【问题描述】:
我有 2 个操作发出 GET 请求并将响应保存在 Vuex 存储中。第一个操作getVersion() 获取游戏的最新版本,并且需要该版本才能发出第二个 GET 请求。现在我已经在第二个操作中对版本进行了硬编码,但是,我的目标是将它连接到 URL 中。
遗憾的是,我不确定如何从函数内部访问它。 Console.log(state.version) 出于某种原因返回 null,即使它不应该是。我从 App.vue 内部调用这些函数,如下所示:
mounted(){
this.$store.dispatch('getVersion')
this.$store.dispatch('getChampions')
}
Vuex 商店
import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
version: null,
champions: null
},
mutations: {
version(state, data){
state.version = data.version
},
champions(state, data){
state.champions = data.champions
}
},
actions: {
getVersion({commit}){
axios.get("http://ddragon.leagueoflegends.com/api/versions.json")
.then((response) => {
commit('version', {
version: response.data[0]
})
})
.catch(function (error) {
console.log(error);
})
},
getChampions({commit, state}){
axios.get("https://ddragon.leagueoflegends.com/cdn/9.24.1/data/en_US/champion.json")
.then((response) => {
commit('champions', {
champions: response.data.data
})
})
.catch(function (error) {
console.log(error);
})
}
},
getters: {
version: (state) => {
return state.version;
},
findChampion: (state) => (id) => {
let championId = id.toString();
let champion = Object.values(state.champions).find(value => value.key === championId);
return champion
}
}
})
【问题讨论】:
标签: javascript vue.js vuex