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