Summary of Vue-CLI2 front end routing usage

Posted by poisedforflight on Sun, 16 Jan 2022 15:41:26 +0100

1. Install Vue router


The reason for using -- save instead of -- save dev here is that it is also needed during generation
npm install vue-router --save 

2. Create a project using Vue cli 2 (router can be installed or not)

If router is installed when creating a project, a router directory will appear in the src directory of the created project, which can be found in the index JS

3. Use Vue router

import Vue from "vue"
import VueRouter from "vue-router"
import home from '../components/Home'
import about from '../components/About'
Vue.use(VueRouter)     //The first step is to install the routing plug-in
const routes=[    //Configuration has relationship
  {
    path:"/home",
    component: home,
  },
  {
    path:"/about",
    component: about
  }
]
const router = new VueRouter({    //The second step is to generate a router object and configure the routing mapping relationship
  routes,    //Configuration has relationship
  mode:"history",    //Specifies whether the router uses history mode or hash mode
  linkActiveClass:"active",
})
export default router    //Step 3: Export (Mount)
<template>
  <div id="app">
    <router-link to="/home" tag="button" replace>homepage</router-link>
    <router-link to="/about" tag="button">about</router-link>
    
    <!-- Code jump mode of routing -->
    <button v-on:click="homeClick">home</button>  
    <button @click="abtClick">about</button>    
    <!-- Code jump mode of routing -->
    
    <!-- Role of space occupying -->
    <router-view></router-view>   
<!--    <router-view/>-->
  </div>
</template>

<script>
export default {
  name: 'App',
  methods:{
    homeClick(){      //Implementation of code jump
      this.$router.push("/home")  //You can also use replace
    },
    abtClick(){     //Implementation of code jump
      this.$router.push("/about")
    }
  }
}

</script>

4. Dynamic routing

The following two effects can be achieved:
  1. Dynamic routing path
  2. Pass simple parameters to later components
Implementation of Dynamic Routing:

  1. Specify the path in a special way when configuring the route
const routes=[
  {
    path:"/",
    redirect: "/home"
  },
  {
    path:"/home",
    component: home,
  },
  {
    path:"/about",
    component: about
  },
  {
    path: '/user/:userId/:number',     //Specify the path in a specific way
    component: User,
  }
]
  1. Dynamic incoming path and use parameters
<template>
  <div id="app">
  	<!-- userName and num The data passed from the back end is dynamically spliced into the path-->
    <router-link :to="'/user/'+userName+'/'+num" tag="button">user</router-link>
    <router-view></router-view>
    <!-- adopt $route.params.userId How to use data-->
    <h1>{{$route.params.userId}}--{{$route.params.number}}</h1>
  </div>
</template>
<script>
export default {
  name: 'App',
  data(){
    return {
      userName:"Li Si",
      num:"2"
    }
  }
}

</script>

5. Use of route lazy loading

Why lazy loading?

When using vue-cli2 for packaging, three JS files will be generated, namely, JS of business logic code, JS of third-party plug-ins, and JS of underlying logic. Here we know that a project will contain many JS files. If all of them are packaged into one file, the user may have a short blank phase in the browser when requesting the JS file because the file is too large. Routing lazy loading is to solve this problem. We only need to return the JS file corresponding to the current url request to the user, instead of returning all the JS files to the user.

There are two ways to implement lazy loading of routes:

const home=()=>import ('../components/Home')      //Mode 1
const about=()=>import('../components/About')
const routes=[
  {
    path:"/",
    redirect: "/home"
  },
  {
    path:"/home",
    component: home,
  },
  {
    path:"/about",
    component: about
  },
  {
    path: '/user/:userId/:number',
    component: ()=>import("../components/User"),    //Mode 2
  }
]

6. Nesting of routes

The first step is to configure nested routes. The second step is to prepare the corresponding components and lazy load the import
const routes=[
  {
    path:"/home",
    component: home,
    children:[    //Using the children keyword
      {
        path:'news',     //The first step is to define the sub path. Note that there is no slash/
        component: ()=>import('../components/home/homeCpnt/News'), // The second step is to prepare the corresponding components and lazy load the import
      },
      {
        path: 'msg',
        component: ()=>import('../components/home/homeCpnt/Message')
      }
    ]
  },
  

Step 3: use the router link and router View Tags in the corresponding parent component

<template>
  <div>
    <h1>Here is home</h1>
    <h2>Here is home Content of</h2>
    <router-link to="/home/news">Journalism</router-link>
    <router-link to="/home/msg">news</router-link>
    <router-view></router-view>
  </div>

</template>

7. Route parameter transfer

There are two ways to pass parameters:
  1. params
    Refer to the dynamic routing section
  2. query

    Step 1: configure routing (normal configuration mode)
const routes=[
  {
    path: '/profile',
    component: ()=>import('../components/profile/Profile')
  }
]
Step 2: dynamically bind the to attribute in the main page, that is, the main APP
<template>
  <div id="app">
    <router-link :to="{path:'/profile',query:{name:'chenchen',age:'18'}}" tag="button">archives</router-link>
    <router-view></router-view>

  </div>
</template>
Step 3: use the transferred data in the sub component
<template>
  <div>
    <h1>Here is profile</h1>
    <h2>Here is profile Content of</h2>
    <h2>{{$route.query.name}}</h2>
    <h2>{{$route.query.age}}</h2>
  </div>
</template>

8. Global navigation guard

What is a navigation guard?
Sometimes we want to deal with something during the jump. Navigation guard is usually used to monitor the jump process, which is similar to vue's life cycle function.
const routes=[
  {
    path:"/",
    redirect: "/home"
  },
  {
    path:"/home",
    component: home,
    children:[
      {
        path:'',
        redirect:'news'
      },
      {
        path:'news',
        component: ()=>import('../components/home/homeCpnt/News'),
      },
      {
        path: 'msg',
        component: ()=>import('../components/home/homeCpnt/Message')
      }
    ],
    meta:{
      title:"homepage"
    }
  },
  {
    path:"/about",
    component: about,
    meta:{
      title:'about'
    }
  },
]
const router = new VueRouter({    
  routes,
  mode:"history",
  linkActiveClass:"active",
})
router.beforeEach((to,from,next)=>{     //Use the navigation guard to change the title of the current label
  document.title=to.matched[0].meta.title
  // console.log(to);
  next()   //Must be called
})

9. Keep alive of components

Make sure that components will not be frequently created and destroyed. The usage is to include router view in the keep alive tag. The keep alive tag contains the include and exclude attributes to exclude or include the specified tag, followed by a string or regular expression. If there are multiple components, use commas to separate them.
<keep-alive exclude="Profile">
  <router-view></router-view>
</keep-alive>

Topics: Java Javascript Vue