Vuex状态不随着突变更新

时间:2020-05-24 06:26:05

标签: javascript vue.js state vuex

我正在尝试将状态的值从false更改为true,但似乎不起作用。在下面,我将添加商店,仅获取状态的组件以及应更新状态的组件。

//存储

export const store = new Vuex.Store({
    state: {
        newComment: false,
        status: ''
    },
    mutations: {
        updateComments(state, payload) {
            state.newComment = payload;
        }
    }
});

//获得状态的组件

<template>
    <div class="home">
        <h1>{{newComment}}</h1>
        <SelectedVideo v-bind:user="user" v-bind:video="videos[0]"/>
    </div>
</template>

<script>
    import axios from 'axios';
    import SelectedVideo from '../components/SelectedVideo.component';
    axios.defaults.withCredentials = true;

    export default {
        name: 'Home',
        components: {
            SelectedVideo
        },
        data() {
            return {
                videos: [],
                user: null
            }
        },
        computed: {
            newComment() {
                return this.$store.state.newComment
            }
        },

//我需要更新状态的组件

methods: {
                updateComments() {
                    this.$store.dispatch('updateComments', true);
                }
            },
            async createComment(comment, video, user) {
                try{
                    const res = await axios({
                        method: 'POST',
                        url: 'http://localhost:8000/api/v1/comments/',
                        data: {
                            comment,
                            video,
                            user
                        }
                    });
                    if (res.data.status === 'success') {
                        console.log(res);
                        // location.reload(true);
                        this.updateComments();
                    }
                } catch(err) {

我已经成功获取状态,但是当我尝试调用要更新的功能时,更新似乎对状态没有影响。

1 个答案:

答案 0 :(得分:0)

首先获取使用状态数据的吸气剂。

getters:{
   get_newComment: state => state.newComment
}

比在您的计算属性中实现它。

computed: {
            newComment() {
                return this.$store.getters.get_newComment
            }
        }

之后,使用“提交”提交一些更改,而不是“发送”。调度用于呼叫操作。