在vuex中状态更改后,vue组件的视图不会重新呈现吗?

时间:2019-10-13 18:14:04

标签: vue.js

最近,我了解了vue及其与之相对应的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.books;
        }
    }
}

我正在通过computed访问vuex商店的书,并且在提交表单数据之后,从vuejs开发人员工具扩展中,我看到了vuex以及组件的计算属性的变化。但是提交后,我看不到视图更新。知道我在这里缺少什么吗?

2 个答案:

答案 0 :(得分:1)

为此,您需要观看

请注意以下示例:

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'
    }
}
  

只是您需要更改手表上的parentKey

watch: {
    books(newVal, oldVal) {
        this.parentKey = Math.random()
    }
}

答案 1 :(得分:0)

问题出在[[0.0, 0.0, 0.0, 0.0, 0.0, .... 3.99, 2.16, 12.23, 0.0, 0.0, 5.07, 7.65, .... 0.0, 0.0, 0.0]] 属性中。应该是:

computed

为方便起见,您可以使用vuex mapGetters

computed: {
 books () {
   return this.$store.getters.books;
 }       
}