当前位置:首页 > VUE

vue实现登录页面跳转

2026-01-21 13:43:08VUE

实现登录页面跳转的核心步骤

使用Vue Router进行路由配置router/index.js中定义登录页和主页的路由:

const routes = [
  {
    path: '/login',
    component: () => import('@/views/Login.vue')
  },
  {
    path: '/home',
    component: () => import('@/views/Home.vue'),
    meta: { requiresAuth: true }
  }
]

创建登录表单组件Login.vue中设置表单提交方法:

methods: {
  handleSubmit() {
    axios.post('/api/login', this.formData)
      .then(response => {
        localStorage.setItem('token', response.data.token)
        this.$router.push('/home')
      })
  }
}

路由守卫实现权限控制

全局前置守卫router/index.js中添加导航守卫:

router.beforeEach((to, from, next) => {
  const isAuthenticated = localStorage.getItem('token')
  if (to.matched.some(record => record.meta.requiresAuth) && !isAuthenticated) {
    next('/login')
  } else {
    next()
  }
})

登录状态管理方案

Vuex存储登录状态 在store中管理用户状态:

state: {
  user: null,
  isAuthenticated: false
},
mutations: {
  SET_USER(state, user) {
    state.user = user
    state.isAuthenticated = true
  }
}

登录成功后更新状态 在登录方法中提交mutation:

this.$store.commit('SET_USER', response.data.user)
this.$router.push({ name: 'Home' })

常见问题处理

路由跳转传参 可通过对象形式传递参数:

this.$router.push({
  path: '/home',
  query: { redirect: from.fullPath }
})

登录后返回原页面 在登录成功后处理redirect参数:

const redirect = this.$route.query.redirect || '/home'
this.$router.push(redirect)

表单验证集成 推荐使用Vuelidate等验证库:

validations: {
  formData: {
    username: { required },
    password: { required, minLength: minLength(6) }
  }
}

vue实现登录页面跳转

标签: 跳转页面
分享给朋友:

相关文章

js实现页面跳转

js实现页面跳转

使用 window.location.href 通过修改 window.location.href 实现页面跳转,直接赋值目标 URL 即可。 window.location.href = '…

vue实现动态显示页面

vue实现动态显示页面

动态显示页面的实现方法 在Vue中实现动态显示页面通常涉及数据绑定、条件渲染、列表渲染以及动态组件等技术。以下是几种常见的实现方式: 数据驱动视图 Vue的核心思想是数据驱动视图,通过修改数据自动…

h5实现登录页面跳转页面跳转页面

h5实现登录页面跳转页面跳转页面

实现H5登录页面跳转 在H5中实现登录页面跳转可以通过多种方式完成,以下是几种常见方法: 使用window.location.href window.location.href = '目标页面…

h5实现页面跳转页面跳转页面

h5实现页面跳转页面跳转页面

H5 实现页面跳转的方法 使用 <a> 标签实现跳转 通过超链接标签 <a> 的 href 属性指定目标页面路径,用户点击后跳转。 <a href="target…

vue 实现页面注册

vue 实现页面注册

Vue 实现页面注册功能 在 Vue 中实现用户注册功能通常需要以下步骤: 创建注册表单组件 使用 Vue 的单文件组件结构创建一个注册表单,包含必要的输入字段如用户名、邮箱、密码等。 <…

js 实现跳转

js 实现跳转

使用 window.location.href 进行跳转 通过修改 window.location.href 可以跳转到指定 URL,浏览器会加载新页面: window.location.hre…