如果用户在Laravel中通过了身份验证,如何检入Vue组件? [英] How to check in a Vue component if a user is authenticated in Laravel?
问题描述
正如标题所述,我有点困惑如何根据用户是否登录并使用Laravel的Auth外观进行身份验证的if/else语句处理Vue组件中的方法.我正在根据用户是否登录发出各种允许/禁止的Axios请求.
As the title states, I'm a little confused how I would tackle a method in my Vue Component with if/else statement based on if the user is logged in and authenticated with Laravel's Auth facade. I'm making various Axios requests which I need to allow/disallow based on if user logged in.
我已经设置了VUEX,并在考虑可以以某种方式使用本地存储来为 isLoggedin 提供一个状态,例如可与Laravel一起使用的状态.但是我不知道这是正确的方法,还是安全并且大概Laravel已经存储了它的身份验证.那么我可以直接在Vue中访问它吗?
I have VUEX setup and was thinking that I can use local storage somehow to have a state for isLoggedin for example that works with Laravel. But I don't know if this is correct method, or secure and presumably Laravel is already storing it's authentication. So can I just access that direct in Vue?
一些我认为不是最好的不干净的解决方案- https://laracasts .com/discuss/channels/vue/hide-button-if-user-is-logged-with-laravel-and-vuejs
Some unclean solutions here that I don't think are the best - https://laracasts.com/discuss/channels/vue/hide-button-if-user-is-logged-with-laravel-and-vuejs
我找不到关于此的任何示例:(
I can not find any examples for this :(
推荐答案
通常,从您的控制器中,将经过身份验证的用户对象传递到视图中,然后将其存储在javascript变量中
Usually from your controller, you pass the authenticated user object into the view which will then be stored in a javascript variable
控制器:
public function index()
{
return view('index', [
'auth_user' => Auth::user()
]);
}
如果用户返回一个对象,则将知道该用户是否已通过身份验证;如果为null,则表示没有用户通过身份验证.
You will know if a user is authenticated if it returns an object or null where null means no user is authenticated.
在刀片中,将auth_user
分配给一个javascript变量:
In your blade, assign the auth_user
into a javascript variable:
<script>
window.auth_user = {!! json_encode($auth_user); !!};
</script>
您的vuex存储对象至少应如下所示:
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;
}
}
}
然后在您的Vue根组件中,获取auth_user
并将其保存到商店中:
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>
您现在基本上有了一个名为this.$store.getters.isLoggedIn
的getter
,您可以在应用程序中使用它来检查用户当前是否已登录.
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.
例如:
这篇关于如果用户在Laravel中通过了身份验证,如何检入Vue组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!