用vue-router重新加载组件 [英] Reload component with vue-router

查看:127
本文介绍了用vue-router重新加载组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用Vuejs和Vue-Router的项目.当用户付款(登录)系统时,服务器返回带有令牌,用户名和名字的文件Json,该文件存储在localstorage中,以用于以下请求.名字在布局中用于在导航栏中显示欢迎消息.注销后,本地存储已清除,问题出在这里,当其他用户在消息中付款时,欢迎使用新的名字重新加载.

I have a project with Vuejs and Vue-Router. When a user pay in (login) system, the server return a file Json with token, username and first name, this file is stored in localstorage for be used in following requests. The first name is used in layout for show a message welcome in the navbar. After logout, localstorage is cleared and the problem is here, when other user pay in the message welcome not reload with new first name.

<v-chip>{{bienvenida}}</v-chip>


computed: {
  bienvenida() {
    const user = JSON.parse(localStorage.getItem("user"));
    return user ? `Bienvenido ${user.firstName}` : "";
  }
}

推荐答案

LocalStorage不是反应性的,因此计算出的属性不会对localStorage的更改做出反应.有各种方法来规避此问题,但最简单的方法是观察内部属性并将值持久保存到localStorage也是.

The LocalStorage is not reactive, so the computed property does not react on a change of the localStorage. There are various ways to circumvent this, but the easiest is, to watch an internal property and just persist the values to the localStorage too.

执行此操作的一种正确方法是使用 Vuex (Vue的官方状态管理)存储您的数据到Vuex存储.然后有一个一个Vuex插件,可将所有商店或部分商店持久保存在本地或会话存储.Vuex商店是反应式的,因此您只需在自己的计算属性中观察商店的更改即可.

One proper way to do this is to use Vuex (official state management of Vue) to store your data to a Vuex store. There is then a Vuex plugin to persist all of the store or parts of it in the local or session storage. The Vuex store is reactive, so you can just watch changes to the store in your computed property.

这篇关于用vue-router重新加载组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆