如何使用 Vuex 和 Axios 发布请求获取最新 ID
Posted
技术标签:
【中文标题】如何使用 Vuex 和 Axios 发布请求获取最新 ID【英文标题】:How to get the latest ID with Vuex and Axios post request 【发布时间】: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'];
,
【问题讨论】:
【参考方案1】:这是因为 createNewPlaceList
是异步的,为了使这个函数异步,一种方法:
placeList.js
const actions =
async createNewPlaceList( commit , url )
await 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);
);
;
组件
methods:
submitForm: async function ()
await 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>
);
,
,
【讨论】:
以上是关于如何使用 Vuex 和 Axios 发布请求获取最新 ID的主要内容,如果未能解决你的问题,请参考以下文章
如何在 Vuex 的操作中使用 axios 获取 Rest API 数据?