Recently, I delved into the world of vue and learned about its redux counterpart vuex. However, I'm facing an issue where changes in the vuex state are not triggering reactive updates to the view in a vue component.
export const store = new Vuex.Store({
state: {
user: {
id: -1,
books: []
}
},
mutations: {
ADD_BOOK(state, book) {
state.user.books.push(book);
}
},
actions: {
addBook(context, book) {
context.commit('ADD_BOOK', book);
}
},
getters: {
books: state => {return state.user.books}
}
})
Within my vue component:
<template>
<div>
...
<div>
<ul>
<li v-for="book in books">
{{ book.name }}
</li>
</ul>
</div>
<div>
<form @submit.prevent="onSubmit()">
<div class="form-group">
<input type="text" v-model="name" placeholder="Enter book name">
<input type="text" v-model="isbn" placeholder="Enter book isbn">
</div>
<button type="submit">Submit</button>
</form>
</div>
...
</div>
</template>
<script>
module.exports = {
data () {
return {
isbn: ''
name: ''
testArr:[]
}
},
methods: {
onSubmit: function() {
let book = {isbn: this.isbn, name: this.name};
this.$store.dispatch('addBook', book);
// If I do `this.testArr.push(book);` it has expected behavior.
}
},
computed: {
books () {
return this.$store.getters.user.books;
}
}
}
After submitting the form data, I can see the changes reflected in both the vuex store and the component's computed property using the vuejs developer tool extension. However, the view is not updating as expected. Any insights on what might be missing here?