不依靠ElementUI实现管理后台界面

本文介绍了如何使用Vue.js配置路由规则,并实现全局前置守卫,确保用户登录状态。通过实例演示了如何在Login、Main和子组件间切换,以及如何存储和清除token。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

整体效果

文件结构:

 main.js

//配置路由规则
const routes = [
  {
    path: '/',
    redirect: '/login',
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/main',
    name: 'main',
    component: () => import('../views/Main.vue'), //懒加载
    children: [
      {
        path: 'userinfo', component: Userinfo, children: [
          { path: 'userdetails', component: Userdetails }
        ]
      },
      { path: 'Shop', component: Shop },
    ],
  }
]
//配置全局前置路由守卫
router.beforeEach((to, from, next) => {
  if (to.path === '/main') {
    const token = localStorage.getItem('token')
    if (token) {
      next()
    } else {
      this.$router.push('/login')
    }
  } else {
    next()
  }
})

export default router

Login.vue

export default {
  data(){
    return{
      username:'',
      password:'',
    }
  },
  methods:{
//登录功能
    login(){
      if(this.username==='admin' && this.password==='1234'){
        localStorage.setItem('token','seccess') //存储token
        this.$router.push('/main')
      }else{
        localStorage.removeItem('token')
      }
    }
  }
}

Main.vue

<template>
  <div id="main">
    <!-- 侧边栏 -->
    <div style="border:1px solid red;width:25%">
      <div class="nav">
        <router-link to="/main/userinfo">userinfo</router-link>
      </div>
      <div class="nav">
        <router-link to="/main/shop">shop</router-link>
      </div>
    </div>

    <!-- 主体 -->
    <div style="border:1px dotted blue;width:100%">
      <router-view />
    </div>
  </div>
</template>

App.vue

<template>
  <div id="app">
    <nav>
      <router-link to="/login">Login</router-link> |
      <router-link to="/main">Main</router-link>
    </nav>
    <button @click="logout">logout</button>
    <router-view/>

  </div>
</template>

export default{
  methods:{
    logout(){
      localStorage.removeItem('token')//清楚token
      this.$router.push('/login')  //跳转登录页
    }
  }
}

userinfo.vue

<template>
  <div>
    userinfo
    <br>
    <!-- 跳转链接 -->
    <router-link to="/main/userinfo/userdetails">userdetails</router-link>

    <div>
      <router-view></router-view>
    </div>
    
  </div>
</template>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值