반응형
vuex를 사용하여 데이터 업데이트
나는 Vuex로서 양식을 사용하여 개체를 업데이트하려고 한다.내 코드 이런 거.
저장 중:
const state = {
categories: []
};
//mutations:
[mutationType.UPDATE_CATEGORY] (state, id, category) {
const record = state.categories.find(element => element.id === id);
state.categories[record] = category;
}
//actions:
updateCategory({commit}, id, category) {
categoriesApi.updateCategory(id, category).then((response) => {
commit(mutationType.UPDATE_CATEGORY, id, response);
router.push({name: 'categories'});
})
}
템플릿 위치.Vue 파일:
<form>
<div class="form-group">
<label for="Name">Name</label>
<input
type="text"
class="form-control form-control-sm"
name="name"
v-model.lazy="category.name" required>
</div>
<div class="form-group">
<label for="Slug">Slug</label>
<input
type="text"
class="form-control form-control-sm"
name="slug"
v-model.lazy="category.slug" required>
</div>
<div class="form-group">
<label for="Avatar">Avatar</label>
<input
type="text"
class="form-control form-control-sm"
name="avatar"
v-model.lazy="category.avatar" required>
</div>
<div class="form-group">
<label for="Description">Description</label>
<textarea
type="text"
class="form-control form-control-sm"
rows="5"
name="description"
v-model.lazy="category.description"></textarea>
</div>
<div class="form-group">
<button type="submit" @click.prevent="updateCategory" class="btn btn-outline btn-sm">Update</button>
</div>
</form>
스크립트:
export default {
data() {
return {
category: {}
}
},
methods: {
getCategoryById(id) {
axios.get(`categories/${id}`)
.then(response => {
this.category = response.data;
})
.catch(error => {
console.log(error);
})
},
// Using mutation.
updateCategory() {
this.$store.dispatch('updateCategory', this.$route.params.id, this.category);
console.log(this.category); //Display exactly data changed.
}
},
created() {
this.getCategoryById(this.$route.params.id);
}
}
내 문제는 내가 업데이트를 클릭할 때야.아무것도 변하지 않는다.나는 인쇄를 했다.category
콘솔의 개체.그것은 내가 기대했던 것을 정확히 보여준다.그러나 업데이트 단추를 누른 후그간 바꾸지 않았다.
그 이유를 말해주고 해결책을 줄 수 있는 사람?고마워요.
매개변수를 1로 묶을 수 있다.payload
객체:
구성 요소
this.$store.dispatch('updateCategory', {
id: this.$route.params.id,
data: this.category
});
당신의 스토어에서 당신은 편집 시 새로운 객체를 만들어야 한다.categories
배열(불변성에 대한 자세한 내용을 읽을 수 있음)
const state = {
categories: []
};
//mutations:
[mutationType.UPDATE_CATEGORY] (state, payload) {
state.categories = state.categories.map(category => {
if (category.id === payload.id) {
return Object.assign({}, category, payload.data)
}
return category
})
}
//actions:
updateCategory({commit}, payload) {
categoriesApi.updateCategory(payload.id, payload.data).then((response) => {
commit(mutationType.UPDATE_CATEGORY, payload);
router.push({name: 'categories'});
})
}
그리고 훨씬 더 간단하다. 어레이를 직접 수정하지 않는 방법(https://vuejs.org/2016/02/06/common-gotchas/#%E2%80%99t-이전 및 DOM 관련 업데이트는 여전히 유효함)
그러니 그냥 당신의 물체를 찾아서 당신의 돌연변이에 있는 이음매로 대체하십시오.
const index = state.objectsArray.map(o => o.id).indexOf(newObject.id);
state.objectsArray.splice(index, 1, newObject);
ES6
업데이트 방법
//mutations UPDATE:
[mutationType.UPDATE_CATEGORY] (state, payload) {
state.categories = [
...state.categories.map(item =>
item.id !== updatedItem.id ? item : {...item, ...updatedItem}
)
]
}
//mutations CREATE:
[mutationType.CREATE_CATEGORY] (state, category) {
state.categories = [category, ...state.categories] //Append to start of array
}
//mutations DELETE:
[mutationType.DELETE_CATEGORY] (state, id) {
state.categories = [
...state.categories.filter((item) => item.id !== id)
];
}
Javascript 객체에 참조 기능이 있기 때문에 하나의 라인 코드만 있으면 된다.
//mutations:
[mutationType.UPDATE_CATEGORY] (state, id, category) {
Object.assign(state.categories.find(element => element.id === id), category);
}
참조URL: https://stackoverflow.com/questions/50416063/update-data-using-vuex
반응형
'programing' 카테고리의 다른 글
하위 프로세스를 종료하는 방법 - _hostname vs. exit (0) | 2022.04.27 |
---|---|
NuxtJs 경로에서 *(아스터스크)를 사용하는 방법? (0) | 2022.04.27 |
C 매크로는 무엇에 유용한가? (0) | 2022.04.27 |
한 구조물을 다른 구조물에 복사 (0) | 2022.04.27 |
상속과 구성의 차이 (0) | 2022.04.27 |