【问题标题】:Vuex map state undefined when it's called from component从组件调用Vuex映射状态未定义
【发布时间】:2020-09-10 07:24:39
【问题描述】:

所以,每当 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。

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

到目前为止,一切正常。每次刷新页面,只要我的本地存储有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?

【问题讨论】:

  • 可能你的组件在你的认证方法完成之前就已经被加载了,为什么它通过 isAuth 是因为 token 是undefined 不是 "" 并且不是 null。
  • 是的,我也这么认为,我是如何解决的?我在 beforeCreate() 中移动了我的身份验证过程,但仍然没有运气。还是想办法解决
  • 更改商店中的方法!!state.token 而不是createdbeforeCreate watch isAuth 当它是true 时设置名称和电子邮件
  • 好吧,我想通了。建议观察者是绝对正确的。但结果还是一样,都是未定义的。检查 isAuth (返回布尔值取决于令牌)以更新我的 vuex 状态不起作用,1)我相信这是因为我的令牌保存在 localStorage 中,它总是在我的 api 身份验证过程之前先获取。 2)我的部分建议组件在我的 auth api 进程完成之前加载。解决方案,而不是监视我的 isAuth,我使用监视程序查看我的 vuex 用户状态以查看是否进行了任何更改。谢谢!你能回答我的问题,以便我投票作为正确答案吗?
  • !!state.store 检查不是null,不是undefined,也不是空字符串。或者你也可以在beforeRoute中添加认证,并在加载令牌时输入路由

标签: javascript vue.js vuex


【解决方案1】:

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

【讨论】:

  • 我试过这个。但还是一样。我在下面发布了解决方案
【解决方案2】:

我找到了解决方案,即:

按照@dreijntjens 的建议,我在“SectionAdvices.vue”中添加了观察者

...
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 调用在这一步之后运行,这是没有意义的。所以,我确实需要观察者,以查看用户状态的任何变化并在此之后更新其组件内的本地数据。

【讨论】:

    猜你喜欢
    • 2018-08-09
    • 2020-05-28
    • 1970-01-01
    • 2021-02-12
    • 2018-09-22
    • 1970-01-01
    • 2021-05-27
    • 2018-11-23
    • 2021-01-18
    相关资源
    最近更新 更多