【问题标题】:Vuex mutation not working synchronously but neither returning a promiseVuex 突变不同步工作但不返回承诺
【发布时间】:2019-09-03 09:41:09
【问题描述】:

我的 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! {…}

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

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

【问题讨论】:

  • 提交是不是可能没有记录(例如状态不活跃)。你看到的是 loadSections() 结束后另一个地方的另一次突变?为了确定,我会在突变代码的开头放一个日志。

标签: javascript vue.js vuex


【解决方案1】:

改变状态的正确方法是在动作内部。

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

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

【讨论】:

  • 我尝试在 vuex 操作中使用相同的代码,据我所知,该操作旨在从商店外部调用,但我得到了相同的行为,
  • 它没有回答@Eduardo 的问题。付诸行动只是最佳实践
猜你喜欢
  • 2019-10-24
  • 1970-01-01
  • 2019-07-30
  • 2021-02-25
  • 1970-01-01
  • 2018-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多