반응형
API 호출을 통해 vuex에 새 개체를 추가하고 이미지 URL을 저장하는 방법
vue를 배우려고 하는데 API에서 데이터를 가져오느라 정신이 없어요. directus를 사용하고 있어요.directus에서 데이터를 가져오기 위한 SDK와 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,
}
Vuex 매뉴얼에 따르면:
원하는 모든 필드를 미리 사용하여 스토어의 초기 상태를 초기화하십시오.
그러나 Vuex 개체에 일부 속성을 추가해야 하는 경우set
방법:
Vue.set(obj, 'newProp', 123)
공식 매뉴얼을 참조하십시오.https://vuex.vuejs.org/guide/mutations.html#mutations-follow-vue-s-reactivity-rules
코드는 다음과 같습니다.
import Vue from 'vue';
import users from './../users';
const state = { models: [] };
const getters = { allModels: state => state.models };
const actions = {
async fetchModels({ commit }) {
const response = await users.getItems('models');
commit('_SET_MODELS', response.data);
},
async getPic({ commit, state }) {
state.models.forEach((element, index) => {
if (element != null) {
users
.getFiles(`/Files${element.image}`)
.then(response => {
console.log('checking if the value is correct', response.data[1].data);
commit('_SET_PIC', { index: index, imgURL: response.data[1].data });
})
// .then(result => commit('_GET_PIC', result.data)) // I don't understand this line
.catch(error => {
throw new Error(`API ${error}`);
});
}
});
},
};
const mutations = {
_SET_MODELS: (state, models) => (state.models = models),
// ADD THIS MUTATION
_SET_PIC: (state, args) => {
let index = args.index;
let imgURL = args.imgURL;
Vue.set(state.models[index], 'imgURL', imgURL);
},
_GET_PIC: (state, models) => (state.models = models),
};
export default { state, getters, actions, mutations };
언급URL : https://stackoverflow.com/questions/60431925/how-to-add-new-object-in-vuex-and-store-image-url-through-api-call
반응형
'programing' 카테고리의 다른 글
Vue.js 2의 컴포넌트에서 이벤트 청취자에 액세스할 수 있습니까? (0) | 2022.11.26 |
---|---|
(function($) {})(jQuery);는 무엇을 의미합니까? (0) | 2022.11.26 |
sql에서 join을 사용하여 like를 사용하는 방법 (0) | 2022.11.26 |
PHP DOMhtml5 태그 오류/경고 (0) | 2022.11.07 |
JavaScript 객체의 컨스트럭터 (0) | 2022.11.07 |