[英]Vue component's view doesn't re-render after state change in vuex?
Recently I picked up on vue and its redux counterpart vuex.最近我学习了 vue 及其 redux 对应的 vuex。 But for some reason changes in state in vuex aren't triggering reactive updates to the view in a vue component.
但是由于某种原因,vuex 中 state 的更改不会触发对 vue 组件中视图的反应更新。
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:在我的 Vue 组件中:
<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.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.我正在通过
computed
访问 vuex 商店的书籍,在我提交表单数据后,从 vuejs 开发人员工具扩展中,我看到了 vuex 的变化以及组件的计算属性。 But I don't see the view getting updated after I submit.但我没有看到提交后视图得到更新。 Any idea what I am missing here?
知道我在这里缺少什么吗?
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只是你需要在手表上更改
parentKey
watch: {
books(newVal, oldVal) {
this.parentKey = Math.random()
}
}
The issue is in the computed
property.问题出在
computed
属性中。 It should be:它应该是:
computed: {
books () {
return this.$store.getters.books;
}
}
For ease you can use vuex mapGetters :为方便起见,您可以使用vuex mapGetters :
import { mapGetters } from 'vuex'
export default {
//..
computed: {
...mapGetters(['books'])
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.