javascript - Vuex中状态更改后Vue组件的视图不会重新渲染?
问题描述
最近我学习了 vue 和它的 redux 对应的 vuex。但是由于某种原因,vuex 中的状态变化不会触发对 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}
}
})
在我的 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.user.books;
}
}
}
我正在访问 vuex 商店的书籍,computed
并且在我提交表单数据后,从 vuejs 开发人员工具扩展中,我看到了 vuex 的变化以及组件的计算属性。但我没有看到提交后视图得到更新。知道我在这里缺少什么吗?
解决方案
问题出在computed
物业上。它应该是:
computed: {
books () {
return this.$store.getters.books;
}
}
为方便起见,您可以使用vuex mapGetters:
import { mapGetters } from 'vuex'
export default {
//..
computed: {
...mapGetters(['books'])
}
}
推荐阅读
- tensorflow - Tensorflow 2:在训练期间获取张量值
- powerbi - DAX 在不相关的表中查找第一个非空白值
- mysql - 存储过程如果条件不起作用 MYSQL
- r - 是否可以增加 R 中的内存限制
- regex - 允许某个文件并排除所有其他文件的正则表达式
- python - OpenCV 或 Numpy 中的对比度拉伸与限制和消隐
- python - Matplotlib Sliders - Autoscaling of the y-axis
- python - Comparing two lists from user input (lottery game)
- ios - Swift WKWebView 没有将全局处理程序注入网站
- django - Django create_superuser() missing 1 required positional argument: 'username'