Keeping logged in user information

冷暖自知 提交于 2019-12-10 21:06:01

问题


I managed to log in with laravel passport. I have the token, great. But I want to keep logged in user information, name, avatar and so on.

My login procedure gets oauth token. In dashboard component I make api call for user data.

Should I keep them in global Vue object or use Vuex? Is it safe?


回答1:


Some options you might consider

  • store data in cookies
  • use localStorage
  • keep everything in the root vue instance
  • keep everything in a wrapping vue component

My suggestion would be to store the auth token - that is actually required to successfully call your backend - in a cookie. This will make it super easy to access it with each and every request you send.

To store the user information I'd suggest to either create a wrapping component or use the root vue instance. The following example should clearify this.

wrapping home component (inline template)

data: function() {
  return { userinfo: {} }
},

created: function() {
  // load your user info
}

Then use it in your index.html / main view

<body>
  <home inline-template>
    <!-- any stuff here -->

    <!-- pass the user prop to every component that is shown in the userinfo -->
    <router-view :user="userinfo"></router-view>
  </home>
</body>  

Your components that are shown in the router-view can then access the user prop

example component

...

props: ['user'],

...

<template>
   <span>{{ user.name }}</span>
</template>

...

IMPORTANT: to make this work you will also need to add props: true to the definition of your route. Everything is explained here in detail: https://router.vuejs.org/en/essentials/passing-props.html

Remark: If you don't want to load userdata in your wrapping component you can load it anywhere else and use an event bus to transfer the results to the wrapping component. However, you should always have only ONE source of truth regarding the user info. Store it only at a single place.




回答2:


I found the session helper really easy to use and it solved the problem of globally using the oauth token:

See: https://laravel.com/docs/5.4/session, heading: The Global Session Helper



来源:https://stackoverflow.com/questions/43469358/keeping-logged-in-user-information

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