【问题标题】:Vue.js/vuex UI not updating on programmatic navigationVue.js/vuex UI 未在编程导航上更新
【发布时间】:2017-02-14 17:15:55
【问题描述】:

在我的 Vue 应用程序中,我有一个用于编辑记录的视图。从该组件中,我 (1) 调用 vuex 操作以将记录保存到数据库中,并且 (2) 调用 $router.push() 以导航回概览视图。 vuex 操作将使用 AJAX 持久化记录,然后将返回的记录推送(替换或附加)到存储中的概览列表。问题是在我进行一些手动导航之前,这些更改不会显示在概览视图中。

vuex/store.js:

import Vue from 'vue'
import Vuex from 'vuex'
import $ from 'jquery'

Vue.use(Vuex)

export default new Vuex.Store({
    state: {
        records: [],
        activeRecord: {}
    },
    mutations: {
        pushRecord: function(state, record) {
            var added = false;
            for (var i = 0; i < state.records.length; i++) {
                if (state.records[i]._id == record._id) {
                    state.records[i] = record;
                    added = true;
                    break;
                }
            }
            if (!added) {
                state.records.push(record);
            }
        }
    },
    actions: {
        saveRecord({ commit, state }) {
            $.ajax({
                type: "POST",
                url: "http://127.0.0.1:8080/record",
                data: JSON.stringify(state.activeRecord),
                dataType: "json",
                contentType: "application/json"
            }).done(function(data) {
                commit("pushRecord", data)
            });
        }
    }
})

RecordDetail.vue(注意后续调度和导航):

export default {
    name: "record-detail",
    computed: {
        record() {
            return this.$store.state.activeRecord
        }
    },
    methods: {
        save: function() {
            this.$store.dispatch("saveRecord")
            this.$router.push({ path: '/records' })
        }
    }
}

【问题讨论】:

    标签: vue.js vuejs2 vue-router vuex


    【解决方案1】:

    在突变中,而不是做:

    state.records[i] = record;
    

    尝试以下:

    Vue.set(state.records, i, Object.assign({}, record))
    

    为什么

    由于 JavaScript 的限制,Vue can't detect 当您直接设置带有索引的项目时,例如vm.items[indexOfItem] = newValue

    您可以执行以下操作之一来克服此问题:

    state.records.splice(i, 1, record)
    

    Vue.set(state.records, i, Object.assign({}, record))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-20
      • 2017-12-22
      • 2017-04-13
      • 1970-01-01
      • 1970-01-01
      • 2017-09-06
      相关资源
      最近更新 更多