【发布时间】:2020-06-20 00:33:07
【问题描述】:
我正在使用带有 Axios 发布请求的 Vuex 在数据库中创建一个新列表,然后我想获取最新的 ID,以便我可以将用户重定向到新创建的列表。我试图使用不同的选项,请参阅下面组件中的console.log,它总是返回 1(默认值)。我怎样才能获得最新的 ID?
我的回复如下:
1 - with getters - 1
2 - with computed - 1
3 - with vuex - 1
0 - 94
index.js
import Vue from 'vue';
import Vuex from 'vuex';
import placeList from './modules/placeList';
Vue.use(Vuex);
export default new Vuex.Store({
modules: {
placeList
},
});
placeList.js
import Axios from 'axios';
const state = {
newId: 1,
name: '',
description: '',
private: 0,
};
const mutations = {
setNewId(state, newId) {
state.newId = newId;
},
};
const getters = {
getNewId: state => {
return state.newId;
}
};
const actions = {
createNewPlaceList({ commit }, url ) {
Axios
.post(url, {
'name': state.name,
'description': state.description,
'private': state.private,
})
.then(response => {
commit('setNewId', response.data.newPlaceListId);
console.log('0 - ' + response.data.newPlaceListId);
})
.catch(errors => {
console.log(errors);
});
}
};
export default {
namespaced: true,
state,
mutations,
actions,
getters
};
组件
import { mapState } from 'vuex';
import { mapGetters } from 'vuex';
export default {
name: "PlaceListCreate",
methods: {
submitForm: function () {
this.$store.dispatch('placeList/createNewPlaceList', <API URL>);
console.log('1 - with getters - ' + this.testNewId);
console.log('2 - with computed - ' + this.anewId);
console.log('3 - with vuex - ' + this.$store.state.placeList.newId);
// Redirect to new created list
this.$router.push({ name: 'active-list', params: {
id: <New ID>
}});
},
},
computed: {
...mapState([
'name',
'description',
'private',
'newId'
]),
...mapGetters([
'getNewId'
]),
anewId() {
return this.$store.state.placeList.newId;
},
testNewId () {
return this.$store.getters['placeList/getNewId'];
}
},
}
【问题讨论】: