How can I redirect back to previous page after login on vue and laravel?

无人久伴 提交于 2019-12-02 13:43:11

问题


I use vue.js 2 and laravel 5.6

My vue component like this :

<template>
    <a v-if="auth" href="javascript:" class="btn btn-default btn-block" @click="add($event)">
        Add
    </a>
    <a v-else href="javascript:" class="btn btn-default btn-block" @click="logout">
        Add
    </a>
</template>
<script>
    export default {
        data() {
            return {
                auth: App.authCheck
            }
        },
        methods: {
            add(event) {
               ...
            },
            logout() {
                window.location = '/login?red='+window.location.pathname
            }
        }
    }
</script>

If the user is not logged in, it will call the logout method

I try like the code above, but if user login, it does not redirect to the previous page

How can I solve this problem?


回答1:


Laravel requires you do do a POST request when logging out.

In order to do this you will need the csrf token and the logout url.

I would pass these 2 as props (in a blade template) :

<my-component 
    logout-url="{{route('logout')}}" 
    csrf-token="{{ csrf_token() }}">
</my-component>

Then you should add a hidden form to your template and add the appropriate logic:

<template>
    <a v-if="auth" href="javascript:" class="btn btn-default btn-block" @click="add($event)">
        Add
    </a>
    <a v-else href="javascript:" class="btn btn-default btn-block" @click="logout">
        Add
    </a>
    <form id="vue-logout-form" v-action="{{ logoutUrl }}" method="POST" style="display: none;">
        <input name="_token" type="hidden" value="{{ csrfToken }}">
    </form>
</template>
<script>
    export default {
        props: {
            logoutUrl:{type: String},
            csrfToken:{type: String}
        },
        [...]
        methods: {
            logout() {
                document.getElementById("vue-logout-form").submit();
            }
        }
    }
</script>

Basically you will make the post request by calling the logout() method



来源:https://stackoverflow.com/questions/49373967/how-can-i-redirect-back-to-previous-page-after-login-on-vue-and-laravel

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