Vue.js Vue组件';s视图没有';在vuex中更改状态后是否重新渲染?
最近我了解了vue及其redux对应的vuex。但由于某些原因,vuex中的状态更改不会触发对vue组件中视图的反应式更新Vue.js Vue组件';s视图没有';在vuex中更改状态后是否重新渲染?,vue.js,Vue.js,最近我了解了vue及其redux对应的vuex。但由于某些原因,vuex中的状态更改不会触发对vue组件中视图的反应式更新 export const store = new Vuex.Store({ state: { user: { id: -1, books: [] } }, mutations: { ADD_BOOK(state, book) { s
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.books;
}
}
}
...
-
{{book.name}
提交
...
module.exports={
数据(){
返回{
isbn:'
名称:“”
testArr:[]
}
},
方法:{
onSubmit:function(){
let book={isbn:this.isbn,name:this.name};
这是。$store.dispatch('addBook',book);
//如果我这样做,它就会有预期的行为。
}
},
计算:{
书籍(){
归还此。$store.getters.books;
}
}
}
我正在通过
computed
访问vuex商店的书籍,在我提交表单数据后,从vuejs开发人员工具扩展中,我看到vuex中的更改以及组件的计算属性。但我没有看到提交后视图得到更新。知道我这里缺少什么吗?问题出在computed
属性中。应该是:
computed: {
books () {
return this.$store.getters.books;
}
}
为方便起见,您可以使用:
要做到这一点,你需要观察 请注意这个例子:
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)
}
}
现在可以重新渲染组件
<template>
<div :key="parentKey">{{books}}</div>
</template>
data() {
return {
parentKey: 'first'
}
}
很抱歉原来我用的是
这个.store.getters.books
。我在我的帖子里抄错了东西。奇怪的事情正在发生。当我在提交后按backspace键时,数据会显示出来。当你按submit键时,数据会显示出来。你能在codepen或codesanbox上创建一个例子来重现这个问题以帮助你吗?当我运行你的代码时,我觉得一切都很好。我唯一需要修复的是数据中属性之间缺少逗号。
<template>
<div :key="parentKey">{{books}}</div>
</template>
data() {
return {
parentKey: 'first'
}
}
watch: {
books(newVal, oldVal) {
this.parentKey = Math.random()
}
}