为了账号安全,请及时绑定邮箱和手机立即绑定

在 vuex 中状态更改后,Vue 组件的视图不会重新渲染?

在 vuex 中状态更改后,Vue 组件的视图不会重新渲染?

元芳怎么了 2021-11-18 20:53:33
最近我开始学习 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 以及组件的计算属性的变化。但是我在提交后没有看到视图得到更新。知道我在这里缺少什么吗?
查看完整描述

2 回答

?
MM们

TA贡献1886条经验 获得超2个赞

问题出在computed物业上。它应该是:


computed: {

 books () {

   return this.$store.getters.books;

 }       

}

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


import { mapGetters } from 'vuex'


export default {

  //..

  computed: {

    ...mapGetters(['books'])

  }

}


查看完整回答
反对 回复 2021-11-18
?
慕田峪7331174

TA贡献1828条经验 获得超13个赞

为此,您需要观看


请注意这个例子:


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()

    }

}


查看完整回答
反对 回复 2021-11-18
  • 2 回答
  • 0 关注
  • 113 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信