87
rated 0 times
[
93]
[
6]
/ answers: 1 / hits: 15546
/ 6 Years ago, fri, may 18, 2018, 12:00:00
As Vuex, I'm trying to update an object using form.
My code like this.
In store:
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'});
})
}
Template in .Vue file:
<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>
And in script:
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);
}
}
My problem is when I click Update. It nothing change.
I did print category
Object in console. It displays exactly what I expected.
But after click Update button. It hasn't changed.
Anyone can tell me why and give me solution?? Thanks.
More From » vue.js