【发布时间】: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