簡體   English   中英

使用Laravel 5.4 API和Vue.js進行用戶身份驗證

[英]User authentication using Laravel 5.4 API and Vue.js

我使用Laravel 5.4創建了一個API,該API在登錄后為我提供了令牌。因此,在Vue.js項目中,我創建了一個auth文件夾和一個index.js文件,以便可以重復使用。

這是我的auth/index.js文件:

import router from '../router'
import axios from 'axios'

export default {
    user: {
        authenticated: false
    },

    login(context, credentials, redirect) {
        axios.post('http://localhost:8000/api/login', credentials)
            .then(response => {
                console.log(response);
                if(response.data.success) {
                    localStorage.setItem('access_token', response.data.token)

                    this.user.authenticated = true;
                    router.go('/');
                }
            })
            .catch(error => {
                context.error = error;
            });
    }
}

這是我的Login.vue組件中的login()方法:

<script>
import axios from 'axios';
import auth from '../../auth/'

export default {
    data() {
        return {
            credentials: {
                login: '',
                password: ''
            }
        }
    },
    methods: {
        login() {
            auth.login(this, this.credentials, 'admin/dashboard');
        }
    }
}
</script>

access_token保存到localStorage之后,我在重定向到路由時遇到麻煩。 該頁面只是刷新,僅此而已。 有什么解決方法?

router.go()VueJS 2.0中已更改。

您現在可以使用router.push({ name: "routerName"})或僅使用router.push("routerName")進行重定向。

檢查文檔: https : //router.vuejs.org/en/essentials/navigation.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM