[英]Assigning Axios fetched data to Vuex State from Vuex Action
根據Axios 文檔 ,我在Vuex存儲的actions
中同時從支持的( block.json
和type.json
)獲取兩個數據源。 在我的Vuex狀態中,我將myBlocks
和myTypes
聲明為數據。 數據可以很好地獲取,但是我似乎無法將獲取的數據分配給處於Vuex狀態的變量。 我似乎在引用狀態時遇到麻煩,因為console.log(state.sample)
產生的是undefined
而不是foo
。 但是, console.log(state)
產生以下內容,如下圖所示。 任何線索都很好。
state: {
sample: 'foo',
myBlocks: [],
myTypes: []
},
actions: {
fetchElementColors: function(state) {
function getElementBlockColors() { return axios.get('/element-data/block.json'); }
function getCategoryDataColors() { return axios.get('/element-data/type.json'); }
axios.all([getElementBlockColors(), getCategoryDataColors()])
.then(axios.spread(function(blockData, categoryData) {
console.log(state);
console.log(state.sample);
state.myBlocks= blockData.data;
state.myTypes= categoryData.data;
}));
}
}
在您的actions
,沒有為您提供state
而是為您提供context
。
因此,您需要執行以下操作:
actions: {
fetchElementColors: function(context) {
function getElementBlockColors() { return axios.get('/element-data/block.json'); }
function getCategoryDataColors() { return axios.get('/element-data/type.json'); }
axios.all([getElementBlockColors(), getCategoryDataColors()])
.then(axios.spread(function(blockData, categoryData) {
console.log(context.state);
console.log(context.state.sample);
context.state.myBlocks= blockData.data;
context.state.myTypes= categoryData.data;
}));
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.