首页 > 解决方案 > 从组件调用时Vuex映射状态未定义

问题描述

因此,每当 vuex 中的状态不为空时,我都会尝试从组件中更新一些数据。我用 laravel 设置了一个 API 路由,在用户登录后返回用户信息。

API 路由:

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 中,在 created 方法中,如果存在令牌,我将使用 http 响应作为有效负载提交 SET_AUTH_USER。

应用程序.vue:

<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>

到目前为止,一切正常。每次我刷新页面时,只要我的本地存储中有一个令牌,用户对象就会一直有用户信息。

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?

标签: javascriptvue.jsvuex

解决方案


您可以尝试使用 getter 获取状态数据吗?因为生命周期。Getter 在组件页面渲染时首先设置


推荐阅读