【发布时间】: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而不是created或beforeCreatewatchisAuth当它是true时设置名称和电子邮件 -
好吧,我想通了。建议观察者是绝对正确的。但结果还是一样,都是未定义的。检查 isAuth (返回布尔值取决于令牌)以更新我的 vuex 状态不起作用,1)我相信这是因为我的令牌保存在 localStorage 中,它总是在我的 api 身份验证过程之前先获取。 2)我的部分建议组件在我的 auth api 进程完成之前加载。解决方案,而不是监视我的 isAuth,我使用监视程序查看我的 vuex 用户状态以查看是否进行了任何更改。谢谢!你能回答我的问题,以便我投票作为正确答案吗?
-
!!state.store检查不是null,不是undefined,也不是空字符串。或者你也可以在beforeRoute中添加认证,并在加载令牌时输入路由
标签: javascript vue.js vuex