vue使用Router

一、项目

vue项目使用@vue/cli 4.0.5搭建,并安装了router路由

二、路由配置

打开src/router/index.js,配置路由:

import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

const router = new Router({
  routes: [
    // 登录
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/login'),
      meta: { title: '登录' }
    },
    // 页面框架
    {
      path: '/',
      component: () => import('@/views/layout'),
      children: [
        // 首页
        {
          path: '/',
          name: 'home',
          meta: {
            title: "首页",
            icon: "home"
          },
          component: () => import('@/views/home')
        },
        // 内容框架
        {
          path: '',
          component: () => import('@/views/layout/body'),
          children: [
            // 配电设施
            {
              path: '/facilities',
              name: 'facilities',
              meta: {
                title: "开关站",
                icon: "tool"
              },
              component: () => import('@/views/facilities')
            },
            // 校区统计
            {
              path: '/campus',
              name: 'campus',
              meta: {
                title: "校区统计",
                icon: "gold"
              },
              component: () => import('@/views/statistics/campus')
            },
            // 配电设施统计
            {
              path: '/facilSta',
              name: 'facilSta',
              meta: {
                title: "开关站统计",
                icon: "tool"
              },
              component: () => import('@/views/statistics/facilSta')
            },
            // 电表统计
            {
              path: '/surface',
              name: 'surface',
              meta: {
                title: "电表统计",
                icon: "dashboard"
              },
              component: () => import('@/views/statistics/surface')
            }
          ]
        }
      ]
    },
  ]
})

// 导航守卫
// 使用 router.beforeEach 注册一个全局前置守卫,判断用户是否登陆
router.beforeEach((to, from, next) => {
  let id = localStorage.getItem('token');  //获取缓存中的用户 token
  if (to.path === '/login') {
    if (id && id != '') {
      next('/');
    }
    next();
  } else {
    if (id === 'null' || id === '' || !id) {
      next('/login');
    } else {
      next();
    }
  }
});

export default router

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容