简体   繁体   English

用vue-router重新加载组件

[英]Reload component with vue-router

I have a project with Vuejs and Vue-Router. 我有一个使用Vuejs和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. 当用户付款(登录)系统时,服务器返回带有令牌,用户名和名字的文件Json,该文件存储在localstorage中以用于以下请求。 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}` : "";
  }
}

The LocalStorage is not reactive, so the computed property does not react on a change of the localStorage. LocalStorage是非反应性的,因此计算出的属性不会对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. 多种方法可以避免这种情况,但最简单的方法是观察内部属性并将值也持久保存到localStorage。

One proper way to do this is to use Vuex (official state management of Vue) to store your data to a Vuex store. 一种适当的方法是使用Vuex (Vue的官方状态管理)将数据存储到Vuex存储中。 There is then a Vuex plugin to persist all of the store or parts of it in the local or session storage. 然后有一个Vuex插件可将所有存储或部分存储持久存储在本地或会话存储中。 The Vuex store is reactive, so you can just watch changes to the store in your computed property. Vuex存储是反应性的,因此您只需在您的计算属性中观察对存储的更改即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM