当从组件调用Vuex map时,Vuex map状态未定义

问题描述 投票:0回答:1

所以,我试图每次从组件中更新一些数据,vuex中的状态不是空的。我用laravel设置了一个API路由,在用户登录后返回用户信息。

API routes:

Route::group(['middleware' => ['auth:api']], function () {
    Route::get('profil', 'Api\UserController@profil')->name('profile'); // will returning user info
}

Vuex:

export default new Vuex.Store({
    state: {
        token: localStorage.getItem('token') || "",
        user: {}
    },
    getters: {
        isAuth: state => {
            return state.token != "" && state.token != null
        }
    },
    mutations: {
        SET_TOKEN(state, payload) {
            state.token = payload
        },
        SET_AUTH_USER(state, payload) {
            state.user = payload
        }
    }
})

所以在我的App.vue中, 在创建的方法中, 我提交了SET_AUTH_USER, 如果token存在的话, 就用http响应作为payload.

在我的App.vue中,我的方法是在创建方法中,如果token存在,我就提交SET_AUTH_USER,并将http响应作为有效载荷。

<template>
  <div id="app-layout">
    <section-advices></section-advices>
</template>

<script>
    import SectionAdvices from "./SectionAdvices"


    export default {
        name: "app-layout",
        components: {
            SectionAdvices
        },
        created() {
            if (this.$store.state.token !== (null || "")) { //check token in vuex state
                this.$http
                    .get("/profil")
                    .then(res => {
                        if (res.status === 200) {
                            this.$store.commit("SET_AUTH_USER", res.data.data); //set $store.state.user with response
                        } else {
                            this.$store.commit("SET_AUTH_USER", null); // set with null
                        }
                     })
                     .catch(err => {
                         console.log(err);
                     });
            }
        }
    }
</script>

每次我刷新页面时,只要我的本地存储中有token,用户对象就会有用户信息。

SectionAdvices.vue:

<template>
    <section class="advices">
        <input type="text" v-model="name">
        <input type="text" v-model="email">
    </section>
</template>

<script>
    import { mapState, mapGetters, mapActions, mapMutations } from "vuex";
        export default {
            name: "section-advices",
            data(){
                return{
                    name: null,
                    email: null
                }
            },
            computed:{
                ...mapState(["user"]),
                ...mapGetters(["isAuth"]),
            },
            created() {
                if(this.isAuth) { //its returning true. the codes below was executed
                    this.name = this.user.name // gives name data with "undefined"
                    this.form.email = this.user.email // it's "undefined" too
                 }
             }
        }
</script>

SectionAdvices组件中的姓名和电子邮件都被设置为 "未定义",尽管在Vue开发工具中,用户对象确实有这些值。我是否在错误的生命周期中调用了App.vue中的api?

javascript vue.js vuex
1个回答
0
投票

你可以尝试使用getters来获取状态数据吗?因为生命周期的关系。获取器是在组件页面渲染时先设置的


0
投票

我找到了解决方法,那就是

按照@dreijntjens的建议,我在我的 "SectionAdvices.vue "中添加了watcher。

...
watch: {
    // watching for store.state.user changes
    user: {
        handler: "fillForm", // call the method
        immediate: true // this watcher will exec immediately after the comp. created
    }
 },
 methods: {
    fillForm() {
        if(this.isAuth) { // this is not necessary, just want to make sure. Once isAuth === true, codes below will be executed
            this.form.name = this.user.name
            this.form.email = this.user.email
        }
    }
 }

所以,真正的问题是,当SectionAdvices.vue创建并获取数据时,store.state.user还是一个空对象。我的API调用在这一步之后运行,这是毫无意义的。所以,我确实需要watcher,来查看用户状态的任何变化,并在这之后更新其组件内的本地数据。

© www.soinside.com 2019 - 2024. All rights reserved.