vue 判断是否登录,未登录跳转到登录页

网页一进入判断是否登录,未登录跳转到登录页面,Vue登录注册,并保持登录状态

router.js


export default new Router({
  routes: [
    {
      path: '/',
      name: 'HelloWorld',
      component: HelloWorld,
      meta: {
        title: '首页',
        type: 'login'  // 是否需要判断是否登录,这里是需要判断
      }
    },
    {
      path: '/login',
      name: 'login',
      component: login,
      meta: {
        title: 'login',
        type: '' // 不需要鉴权
      }
    }
  ]
})

main.js


router.beforeEach((to, from, next) => {
  if (to.meta.title) {
    document.title = to.meta.title
  }
  const type = to.meta.type
  // 判断该路由是否需要登录权限
  if (type === 'login') {
    if (window.localStorage.getItem('login')) {
      next()
    } else {
      next('/login')
    }
  } else {
    next()  // 确保一定要有next()被调用
  }
})

来源:https://segmentfault.com/a/1190000016889438

  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
要实现登录登录页面的功能,可以在 Vue3 中使用 Vue Router。具体实现步骤如下: 1. 安装 Vue Router: ``` npm install vue-router ``` 2. 在项目中创建一个路由实例: ``` import { createRouter, createWebHistory } from 'vue-router' const router = createRouter({ history: createWebHistory(), routes: [ // 定义路由 { path: '/login', component: Login }, { path: '/home', component: Home, meta: { requireAuth: true // 添加该字段,表示进入这个路由是需要登录的 } } ] }) export default router ``` 这里定义了两个路由,一个是登录页面 `/login`,另一个是需要登录才能访问的页面 `/home`。注意,`/home` 路由添加了一个 `meta` 字段,用来表示该路由需要登录才能访问。 3. 在路由实例中添加一个全局前置守卫: ``` router.beforeEach((to, from, next) => { if (to.meta.requireAuth) { // 判断该路由是否需要登录权限 if (localStorage.getItem('token')) { // 通过 token 判断是否已经登录 next() } else { next({ path: '/login', query: { redirect: to.fullPath } // 将的路由 path 作为参数,登录成功后到该路由 }) } } else { next() } }) ``` 该守卫会在每个路由之前执行,用来判断用户是否已经登录。如果用户已经登录,则直接到目标路由;如果用户登录,则登录页面,并将目标路由的 path 作为参数传递过去。 4. 在组件中使用路由: ``` <template> <div> <button @click="gotoHome">进入首页</button> </div> </template> <script> export default { methods: { gotoHome() { this.$router.push('/home') } } } </script> ``` 通过 `this.$router.push('/home')` 可以实现路由。 这样,当用户登录时,访问需要登录才能访问的页面时,就会被自动登录页面。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值