我正在尝试学习 vue,但我坚持从 API 获取数据。我正在使用 directusSDK 从 directus 获取数据,并且我能够从 API 获取数据,但我无法将图像 URL 存储在状态的新对象中,有人可以告诉我如何在状态中添加新对象属性并将图像 URL 存储在其上.
这是我的代码
store/modules/models.js
import users from "./../users"
const state =
{
models: []
};
const getters =
{
allModels: state =>state.models
};
const actions =
{
async fetchModels({ commit }) {
const response = await users.getItems("models");
//console.log(response.data);
commit('_SET_MODELS', response.data);
},
async getPic({commit, state}){
state.models.forEach((element)=>{
if (element != null) {
users.getFiles("/Files"+ element.image)
.then(response => {
element["imgURL"] = response.data[1].data
}).then(result => commit('_GET_PIC', result.data)).catch(error => {
throw new Error(`API ${error}`);
})
}
})
}
};
const mutations =
{
_SET_MODELS: (state, models) => (state.models = models),
_GET_PIC: (state, models) => (state.models = models)
};
export default {
state,
getters,
actions,
mutations,
}
成功获取 imgUrl 我对我的代码进行了更改,并从 API 获取了 imgUrl,但现在的问题是它没有得到正确的 imgUrl,而是分配了随机的 imgUrl。
这是我更新的代码:
import Vue from 'vue'
import users from "./../users"
const state = {
models: [],
picture: []
};
const getters = {
allModels: state => state.models
};
const actions = {
async fetchModels({commit}) {
await users.getItems("models").then(
response => {
commit('_SET_MODELS', response.data)
}
);
var arrModels = state.models;
arrModels.forEach((element, index) => {
users.getFiles("/Files/" + element.image)
.then(response => {
//console.log(response.data[index].data.full_url);
commit('_SET_PIC', {
index: index,
imgURL: response.data[index].data.full_url
});
})
})
}
};
const mutations = {
_SET_MODELS: (state, models) => (state.models = models),
_SET_PIC: (state, args) => {
let index = args.index;
let imgURL = args.imgURL;
Vue.set(state.models[index], 'imgURL', imgURL);
}
};
export default {
state,
getters,
actions,
mutations,
}