首页 > 解决方案 > 如果用户在 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

我找不到任何例子:(

标签: laravelauthenticationvue.jsvuex

解决方案


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:


推荐阅读