Reload component with vue-router

三世轮回 提交于 2021-01-29 09:40:20

问题


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}` : "";
  }
}

回答1:


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.

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.



来源:https://stackoverflow.com/questions/53468414/reload-component-with-vue-router

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!