laravel - 如果用户在 Laravel 中经过身份验证,如何签入 Vue 组件?
问题描述
正如标题所述,我有点困惑如何根据用户是否登录并使用 Laravel 的 Auth 门面进行身份验证,使用 if/else 语句来处理我的 Vue 组件中的方法。我正在发出各种 Axios 请求,我需要根据用户是否登录来允许/禁止这些请求。
我有 VUEX 设置,并认为我可以以某种方式使用本地存储来获得isLoggedin的状态,例如与 Laravel 一起使用。但我不知道这是否是正确的方法,或者是安全的,并且大概 Laravel 已经存储了它的身份验证。那么我可以直接在 Vue 中访问吗?
这里有一些我认为不是最好的不干净的解决方案 - https://laracasts.com/discuss/channels/vue/hide-button-if-user-is-logged-with-laravel-and-vuejs
我找不到任何例子:(
解决方案
Usually from your controller, you pass the authenticated user object into the view which will then be stored in a javascript variable
Controller:
public function index()
{
return view('index', [
'auth_user' => Auth::user()
]);
}
You will know if a user is authenticated if it returns an object or null where null means no user is authenticated.
In your blade, assign the auth_user
into a javascript variable:
<script>
window.auth_user = {!! json_encode($auth_user); !!};
</script>
your vuex store object should atleast look like this:
{
state: {
user: null
},
mutations: {
setAuthUser(state, user) {
state.user = user;
}
},
getters: {
isLoggedIn(state) {
return state.user !== null;
}
}
}
Then in your Vue root component, get the auth_user
and save it into the store:
<script>
export default {
mounted() {
this.$store.commit('setAuthUser', window.auth_user);
}
}
</script>
You now basically have a getter
called this.$store.getters.isLoggedIn
that you can use in your application for checking if a user is currently logged in.
e.g:
推荐阅读
- javascript - 创建一个键相同且值来自数组的对象
- debugging - 我们应该在发布到符号服务器的 PDB 中使用嵌入式调试符号还是完整调试符号?
- tfs - Get latest source code in TFS Visual Studio
- powershell - 如何将 $env:LC_ALL='C.UTF-8' 放在 Powershell 的配置文件中?
- npm-install - 错误:EPERM:不允许操作,mkdir 'C:\Users\xxxxxxx'
- python - 如何使用带有轮廓场、矢量场和移动框的 matplotlib 制作视频?
- javascript - 在点击 Javascript 之前执行按钮方法
- php - 加快大数据的高斯消除php代码
- javascript - 多次下载适用于网络,但不适用于移动设备
- java - 使用 BeanUtils.copyProperties 从 Mybatis 创建的对象到 Spring Bean,Spring bean 中的属性为空。为什么?