Vue 路由一

这里主要讲解开发过程 使用 路由 的思路,而不是讲解router的概念或知识点。关于知识点的讲解与详细内容可以查看官网
https://cn.vuejs.org/v2/guide/routing.html
https://router.vuejs.org/

  • 一个非常简单的路由
  • 使用vue-router管理路由
  • 在页面加载前后,添加功能和权限控制

一个非常简单的路由

如果你只需要非常简单的路由而不想引入一个功能完整的路由库,可以像这样动态渲染一个页面级的组件:

// main.js
import Vue from 'vue';

const routes = {
  '/': Home,
  '/about': About
};

const app = new Vue({
  el: '#app',
  data: {
    currentRoute: window.location.pathname
  },
  computed: {
    ViewComponent() {
      const matchingView = routes[this.currentRoute];
      return matchingView
        ? require('./views/pages/' + matchingView + '.vue')
        : require('./views/pages/404.vue');
    }
  },
  render(h) {
    return h(this.ViewComponent);
  }
});

window.addEventListener('popstate', () => {
  app.currentRoute = window.location.pathname;
});

使用vue-router管理路由

  • 添加 vue-router
npm i vue-router
  • 创建关于 router 的文件


    Vue 路由一_第1张图片
    router.png
// router/index.js
import Vue from 'vue';
import Router from 'vue-router';
Vue.use(Router);

import { routes } from './routes';

const router = new Router({
  mode: 'history',
  // base: process.env.BASE_URL,
  routes: routes
});

export default router;
// router.routes.js
export const routes = [
  {
    path: '/',
    name: 'basic-layout',
    component: () =>
      import(/* webpackChunkName: "layout" */ '../layouts/basic-layout'),
    children: [
      {
        path: '/',
        redirect: '/hello-world'
      },
      {
        path: '/hello-world',
        name: 'hello-world',
        component: () =>
          import(/* webpackChunkName: "hello-world" */ '../views/hello-world')
      },
      {
        path: '*',
        name: '404',
        component: () => import(/* webpackChunkName: "404" */ '../views/404')
      }
    ]
  }
];

  • 在 main.js 中Vue使用 router。当然 App.vue 也要做一些修改
// main.js
import Vue from 'vue';
import App from './App.vue';
import router from './router';

Vue.config.productionTip = false;

new Vue({
  render: h => h(App),
  router
}).$mount('#app');
// App.vue



在页面加载前后,添加功能和权限控制

router.beforeEach 
router.afterEach

一般在页面加载前要 显示页面加载进度条判断是否登录判断页面的访问权限判断页面内部的操作权限等。

import Vue from 'vue';
import { checkAuthority, isLogin } from '../utils/auth';
import NProgress from 'nprogress';
import Router from 'vue-router';
Vue.use(Router);

import { routes } from './routes';

const router = new Router({
  mode: 'history',
  // base: process.env.BASE_URL,
  routes: routes
});

router.beforeEach((to, from, next) => {
  if (to.path !== from.path) {
    NProgress.start();
  }

  if (isLogin()) {
    if (to.path === '/login') {
      next({ path: '/' });
    } else if (checkAuthority(to.path)) {
      next();
    } else {
      next({ path: '/403' });
    }
  } else {
    next({ path: '/user/login' });
  }
});

router.afterEach(transition => {
  NProgress.done(true);
});

export default router;

你可能感兴趣的:(Vue 路由一)