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.

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?

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 :(

推荐答案

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.

在blade中,将auth_user分配到javascript变量中:

<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>

现在基本上有一个名为this.$store.getters.isLoggedIngetter,可以在应用程序中用于判断用户当前是否登录.

例如:

Laravel相关问答推荐

Laravel FAKER语法

如何使用 Laravel 进行继承

Dompdf 古吉拉特语和印地语文本未正确显示

assertSee 由于 html 代码中的空格而失败

单个对象的Eloquent 计数是错误的

Laravel:在失败时处理 findOrFail()

所有 POST 请求上的 Laravel 4 CSRF

使用 Amazon S3 的 Storage::get() 返回 false

插入重复键时,laravel eloquent 忽略错误

Mockery 和 Laravel 构造函数注入

Homestead:文件夹映射到错误的文档根目录

如何在中间件 Laravel 中获取请求的控制器和操作的名称

如何在 Laravel 5.5 中为选定的请求类设置自定义响应

升级到 Laravel 5.2 会使所有会话失效

laravel 5.4 指定的key太长,为什么数字191

Grammar::parameterize() 必须是数组类型

Laravel 5.4 Vue.JS 无法挂载组件:未定义模板或渲染函数

使用 Queue::fake() 测试监听器

如何使用队列设置高、低和中优先级Electron邮件?

Laravel - artisan不工作