[英]How to reload localStorage VueJS after using this.$router.go(-1);
This is my Login.vue:这是我的 Login.vue:
mounted() {
if (localStorage.login) this.$router.go(-1);
},
methods: {
axios.post(ApiUrl + "/login") {
...
}
then(response => {
...
localStorage.login = true;
this.$router.go(0); /* Reload local storage */
})
}
App.vue:应用程序.vue:
mounted() {
axios
.get("/user")
.then(response => {
localStorage.user_id = response.data.user.id;
localStorage.package_id = response.data.user.package_id;
})
},
Project.vue:项目.vue:
mounted() {
this.user_id = localStorage.user_id
this.package_id = localStorage.package_id
}
With that above code, I cannot get localStorage.user_id
and localStorage.package_id
as I expected.使用上面的代码,我无法按预期获得
localStorage.user_id
和localStorage.package_id
。 But if I change like the follow, it worked.但是如果我像下面这样改变,它就起作用了。
mounted() {
const self = this
setTimeout(function () {
self.user_id = localStorage.user_id
self.package_id = localStorage.package_id
self.getProject();
},1000)
}
But I think setTimeout
not good in that case.但我认为
setTimeout
在这种情况下不好。 Is there any way to refactor this code?有没有办法重构这段代码? Thank you!
谢谢!
Try this: in your root component (it's usually const app = new Vue({ ... })
) write the following:试试这个:在你的根组件(通常是
const app = new Vue({ ... })
)中写入以下内容:
import {localStorage} from 'localStorage'; // import your module if necessary
// this is relative to the way you manage your dependencies.
const app = new Vue({
//...
data: function() {
return {
localStorage: localStorage;
}
}
})
Now whenever you want to use localStorage
, access it from root component like this:现在,无论何时您想使用
localStorage
,都可以从根组件访问它,如下所示:
this.$root.localStorage
Hope this solves your problem.希望这能解决您的问题。
Don't know your project structure ,but I guess it's probably an async issue.不知道你的项目结构,但我想这可能是一个异步问题。 You got the user information async, so when
Project.vue
mounted, the request is not complete yet.你得到了异步的用户信息,所以当
Project.vue
挂载时,请求还没有完成。 As a result, the localstorage is empty at the monent.结果,本地存储在 monent 是空的。
There are two solutions for this:对此有两种解决方案:
Make sure Project.vue
is not rendered before userinfo is complete.确保在 userinfo 完成之前未呈现
Project.vue
。 For example, things like <project v-if="userinfo.user_id" />
should works.例如,像
<project v-if="userinfo.user_id" />
应该可以工作。
Use some data binding libary like vuex
to bind userinfo to Project.vue
instead of assign it in lifecycle like mounted
or created
.使用一些数据绑定libary像
vuex
到绑定到用户信息Project.vue
代替像在生命周期分配给它的mounted
或created
。
Hope it helps.希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.