Home  >  Article  >  Web Front-end  >  How to implement lazy loading of routes in vue-router

How to implement lazy loading of routes in vue-router

亚连
亚连Original
2018-06-21 10:57:302010browse

This article mainly introduces the relevant information about lazy loading and permission control of vue-router routing

Lazy loading and permission control of vue-router routing. Today I just made a small demo based on node token verification

So the following is an introduction to lazy loading of routes

1. Why should we use lazy loading of routes?

When writing a single-page application with vue.js, The packaged JavaScript package will be very large, affecting page loading. We can use lazy loading of routes to optimize this problem. When we use a certain route, we will load the corresponding components, which will be more efficient

2. Usage

import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
export default new Router({
 routes: [
  {
   path: '/',
meta: {
requiresAuth: true
},
   component: resolve => require(['components/Hello.vue'], resolve)
  },
  {
    path: '/about',
    component: resolve => require(['components/About.vue'], resolve)
  }
 ]
})

3. Control permissions on routing hooks

//注册全局钩子用来拦截导航

router.beforeEach((to, from, next) => {
 //获取store里面的token
 let token = store.state.token;
 //判断要去的路由有没有requiresAuth
 if(to.meta.requiresAuth){
  if(token){
   next();
  }else{
   next({
    path: '/login',
    query: { redirect: to.fullPath } 
// 将刚刚要去的路由path(却无权限)作为参数,方便登录成功后直接跳转到该路由
   });
  }
 
 }else{
  next();//如果无需token,那么随它去吧
 }
});

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

How to use js to achieve the focus map effect

How to use JQUERY to implement multiple AJAX requests

Recording the number of occurrences of repeated elements in JavaScript

The process of encapsulating and submitting data in the form

The above is the detailed content of How to implement lazy loading of routes in vue-router. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn