Vuex突变无法同步运行,但都无法返回承诺

时间:2019-04-12 15:15:04

标签: javascript vue.js vuex

我的vuex变异似乎无法同步工作。看起来像这样:

mutations: {
    computeStatusData(state, status) {
        if (status.active !== true) { return }

        const started = new Date(status.startedAt);
        started.setHours(0, 0, 0, 0);
        const today = new Date();

        status.currentDay = Math.floor((today.getTime() - started.getTime()) / (1000 * 60 * 60 * 24));
        status.currentWeek = Math.floor(status.currentDay / 7);

        if (!status.programm.sections) { console.log('No Sections'); return; }

        for (let i = 0; i < status.programm.sections.length; i++) {
            if (status.currentWeek <= status.programm.sections[i].to) {
                status.currentSection = i;
                console.log('Current Section', status.currentSection)
                break;
            }
        }
        console.log('new status!', status)
    },

在我组件的方法中,我这样称呼它:

    async loadSections() {

        await somethingElse();

        if (this.status && this.programm.sections) {
            console.log('Recomputing Status')
            this.status.progamm = this.programm;
            this.$store.commit('computeStatusData', status);
            console.log('updated Status', this.status)
        }

        this.$nextTick(() => { this.$forceUpdate(); }) 
    },

我的控制台日志如下:

Recomputing Status
updated Status {…}
Current Section 0
new status! {…}

如果突变是同步的,则应在Current Section 0之前记录new Status!updated Status,但不是。

它似乎没有返回Promise,因为当我执行console.log(this.$store.commit('computeStatusData', status));时,它仅记录undefined

1 个答案:

答案 0 :(得分:0)

更改状态的正确方法是在操作内部。

https://vuex.vuejs.org/guide/actions.html

一个有用的问题: Vuex Action vs Mutations