2017-02-14 17 views
0

在我的Vue應用程序中,我有一個編輯記錄的視圖。從該組件中,我(1)調用vuex操作將記錄保存到數據庫,(2)調用$router.push()導航回總覽視圖。 vuex操作將使用AJAX持續記錄,然後將返回的記錄推送(替換或追加)到商店中的概覽列表。問題在於,除非我進行一些手動導航,否則這些更改不會顯示在總覽視圖中。Vue.js/vuex UI在編程導航上沒有更新

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' }) 
     } 
    } 
} 

回答

2

在變異,而不是做:

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