Reputation: 5856
Recently I picked up on vue and its redux counterpart vuex. But for some reason changes in state in vuex aren't 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}
}
})
In 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;
}
}
}
I am accessing vuex store's books via computed
and after I submit the form data, from vuejs developer tool extension, I see the changes in vuex as well as component's computed property. But I don't see the view getting updated after I submit. Any idea what I am missing here?
Upvotes: 1
Views: 8330
Reputation: 534
To do this you need to watch
Please note this example:
methods: {
...
},
computed: {
books () {
return this.$store.getters.books;
}
},
watch: {
books(newVal, oldVal) {
console.log('change books value and this new value is:' + newVal + ' and old value is ' + oldVal)
}
}
now you can re-render your component
<template>
<div :key="parentKey">{{books}}</div>
</template>
data() {
return {
parentKey: 'first'
}
}
just you need to change
parentKey
on watch
watch: {
books(newVal, oldVal) {
this.parentKey = Math.random()
}
}
Upvotes: 1
Reputation: 27819
The issue is in the computed
property. It should be:
computed: {
books () {
return this.$store.getters.books;
}
}
For ease you can use vuex mapGetters:
import { mapGetters } from 'vuex'
export default {
//..
computed: {
...mapGetters(['books'])
}
}
Upvotes: 3