这是我的 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 */
})
}
应用程序.vue:
mounted() {
axios
.get("/user")
.then(response => {
localStorage.user_id = response.data.user.id;
localStorage.package_id = response.data.user.package_id;
})
},
项目.vue:
mounted() {
this.user_id = localStorage.user_id
this.package_id = localStorage.package_id
}
使用上面的代码,我无法按预期获取 localStorage.user_id
和 localStorage.package_id
。但如果我像下面这样改变,它就起作用了。
mounted() {
const self = this
setTimeout(function () {
self.user_id = localStorage.user_id
self.package_id = localStorage.package_id
self.getProject();
},1000)
}
但我认为 setTimeout
在这种情况下不好。有没有办法重构这段代码?
谢谢!
最佳答案
试试这个:在你的根组件(通常是 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;
}
}
})
现在,每当您想使用localStorage
时,请从根组件访问它,如下所示:
this.$root.localStorage
希望这能解决您的问题。
关于javascript - 如何在使用 this.$router.go(-1); 后重新加载 localStorage VueJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59748299/