Как получить последний идентификатор с помощью Vuex и Ax ios после запроса - PullRequest
4 голосов
/ 07 марта 2020

Я использую Vuex с пост-запросом Ax ios, чтобы создать новый список в базе данных, затем я хотел бы получить последний идентификатор, чтобы я мог перенаправить пользователя во вновь созданный список. Я пытался использовать разные опции, смотрите console.log в компоненте ниже, он всегда возвращает 1 (значение по умолчанию). Как я могу получить последний идентификатор?

Мой ответ выглядит следующим образом:

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 Ответ

1 голос
/ 07 марта 2020

Это происходит потому, что createNewPlaceList является асинхронным, чтобы сделать эту функцию асинхронной c, в одну сторону:

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>
            }});
        },
    },
...