简体   繁体   English

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

[英]How to access Vuex state property from a Vuex action?

Currently I have a store with 2 state properties - version and champions + 2 actions that make GET requests and then commit to the state. 目前,我有一个具有2个状态属性的商店-版本和冠军+ 2个发出GET请求然后提交到该状态的操作。 The second GET requests URL needs to include the version which I've gotten from the first GET request as shown here: 第二个GET请求URL需要包含我从第一个GET请求获得的版本,如下所示:

axios.get("https://ddragon.leagueoflegends.com/cdn/" + X + "/data/en_US/champion.json")

The X in this code is supposed to be the Vuex state version property. 该代码中的X应该是Vuex状态版本属性。 If I wanted to access that property from outside the Vuex store, I would do it like this: 如果我想从Vuex商店外部访问该属性,则可以这样操作:

this.$store.state.version

This doesn't seem to work when I try it in the store though. 但是,当我在商店中尝试时,这似乎不起作用。 How am I supposed to access the version state property from inside the getChampions action? 我应该如何从getChampions操作内部访问版本状态属性?

Code: 码:

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);
            })
        }
    }
})

you should add another atribute to your function that requires to access state: 您应该在需要访问状态的函数中添加另一个属性:

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);
            })
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM