#搭建Vue+TypeScript项目(四)

vue-router的使用

模块化路由

1.在src文件夹下新建router文件夹,新建router.ts(包含路由拦截器)

import Vue from 'vue';
import Router from 'vue-router';
import store from '@/store';
import login from '@/router/login/index';
import home from '@/router/home/index';

Vue.use(Router);

const router = new Router({
  mode: 'history',
  routes: [...home, ...login]
});
// 导航守卫(路由拦截)
router.beforeEach((to, from, next) => {
  
  // 如果没登录,就跳到登录页
  const isLogin: boolean = store.getters.isLogin;
  if (isLogin) {
    next();
  } else {
    if ('/login'.indexOf(to.path) !== -1) {
      next();
    } else {
      next(`/login`);
    }
  }
});
export default router;

2.在src/router文件夹下建login文件夹,新建login.ts(登录路由模块)

export default [
  {
    path: '/login',
    name: 'login',
    component: () => import(/* webpackChunkName: "login" */ '@/views/Login.vue')
  }
];

2.在src/router文件夹下建home文件夹,新建home.ts(主路由模块)

import Home from '@/App.vue';

export default [
  {
    path: '/',
    name: 'home',
    component: Home,
    redirect: '/page1',
    children: [
      {
        path: '/page1',
        name: 'page1',
        // route level code-splitting
        // this generates a separate chunk (about.[hash].js) for this route
        // which is lazy-loaded when the route is visited.
        component: () =>
          import(/* webpackChunkName: "login" */ '@/views/home/Page1.vue')
      },
      {
        path: '/page2',
        name: 'page2',
        // route level code-splitting
        // this generates a separate chunk (about.[hash].js) for this route
        // which is lazy-loaded when the route is visited.
        component: () =>
          import(/* webpackChunkName: "login" */ '@/views/home/Page2.vue')
      }
    ]
  }
];

你可能感兴趣的:(#搭建Vue+TypeScript项目(四))