Vue2+Laravel RESTful API登录系统实现登录后重定向至首页
Hey there! Let's get that post-login redirect sorted out. Looking at your code, the main issue is you haven't added any redirect logic in the successful response handler—right now you're just logging the response. Here's how to fix it:
Option 1: Use Vue Router (Recommended for SPAs)
If you're using Vue Router (standard for most Vue single-page apps), you can leverage $router.push() to navigate to your home page without a full reload.
Update your loginPost method like this:
methods:{ loginPost(){ let vm = this; axios.post('/login', vm.loginDetails) .then(function (response) { console.log(response); // Add this line to redirect to home vm.$router.push('/'); }) .catch(function (error) { // Your existing error handling code stays the same var errors = error.response if(errors.statusText === 'Unprocessable Entity'){ if(errors.data){ if(errors.data.email){ vm.errorsEmail = true vm.emailError = _.isArray(errors.data.email) ? errors.data.email[0]: errors.data.email } if(errors.data.password){ vm.errorsPassword = true vm.passwordError = _.isArray(errors.data.password) ? errors.data.password[0] : errors.data.password } } } }); } }
Quick check: Make sure Vue Router is properly set up in your project. In your
main.js, you should have something like this to inject the router into your Vue instance:import Vue from 'vue' import VueRouter from 'vue-router' import routes from './routes' Vue.use(VueRouter) const router = new VueRouter({ routes, mode: 'history' // Optional, for clean URLs without the # }) new Vue({ router, render: h => h(App) }).$mount('#app')
Option 2: Full Page Redirect (If Not Using Vue Router)
If you're not using Vue Router and need a full page reload, use vanilla JavaScript to redirect:
.then(function (response) { console.log(response); window.location.href = '/'; // Redirects to home page with a full reload })
Extra Things to Verify
- Make sure your Laravel
/loginAPI endpoint returns a 200 OK JSON response on successful login. If it returns a traditional redirect (like Laravel's default web login behavior), axios will follow that redirect internally instead of letting Vue handle it—so adjust your endpoint to send a success JSON payload instead. - Double-check that your home route (
/) is correctly configured either in Vue Router's route list or Laravel's web routes file.
内容的提问来源于stack exchange,提问作者Sid Heart

