如何从 Vuex 操作访问 Vuex 状态属性?

Bob*_*aru 8 javascript vue.js vuex vuejs2

目前我有一个带有 2 个状态属性的商店 - 版本和冠军 + 2 个发出 GET 请求然后提交到状态的操作。第二个 GET 请求 URL 需要包含我从第一个 GET 请求中获得的版本,如下所示:

axios.get("https://ddragon.leagueoflegends.com/cdn/" + X + "/data/en_US/champion.json")
Run Code Online (Sandbox Code Playgroud)

这段代码中的 X 应该是 Vuex 状态版本属性。如果我想从 Vuex 商店外部访问该属性,我会这样做:

this.$store.state.version
Run Code Online (Sandbox Code Playgroud)

但是,当我在商店中尝试时,这似乎不起作用。我应该如何从 getChampions 操作内部访问版本状态属性?

代码:

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}){
            axios.get("https://ddragon.leagueoflegends.com/cdn/" + X + "/data/en_US/champion.json")
            .then((response) => {
                commit('champions', {
                    champions: response.data.data
                })
            })
            .catch(function (error) {
                console.log(error);
            })
        }
    }
})
Run Code Online (Sandbox Code Playgroud)

小智 25

您应该为需要访问状态的函数添加另一个属性:

getChampions({commit, state}){
            axios.get("https://ddragon.leagueoflegends.com/cdn/" + state.version + "/data/en_US/champion.json")
            .then((response) => {
                commit('champions', {
                    champions: response.data.data
                })
            })
            .catch(function (error) {
                console.log(error);
            })
        }
Run Code Online (Sandbox Code Playgroud)