The Router implementation step

1. Create index in the router folder under SRC

Ps :Home and About are both pages under view file

import Vue from 'vue';
/ / 1. Imported
import VueRouter from 'vue-router';
// 2. Modularity mechanism uses router
Vue.use(VueRouter)
import Home from '@/views/Home';
import About from '@/views/About';
// 3. Create router objects
export default new VueRouter({
  routes:[
    {
      path:"/".component:Home
    },
    {
      path:"/about".component:About
    }
  ]
})
Copy the code

2. Next, import the router in SRC main.js and mount the router on the instance

import Vue from 'vue'
import App from './App.vue'
/ / 4. The import into the router
import router from './router'

Vue.config.productionTip = false

new Vue({
  // 5. Mount to the instance
  router,
  render: h= > h(App)
}).$mount('#app')
Copy the code

3. Finally, in app. vue under SRC, use router-link to link routing components and use router-view to render components

<template> <div id="app"> <! - / / 6 matching routing router - the link is equivalent to a tag to attribute is equal to the href -- > < the router - link to = '/' > homepage | < / router - the link > < the router - the link To ='/about'> </router-link> <! <router-view></router-view> </div> </template>Copy the code

After routing

Name the route in the index file on the router

Add a name attribute to each routing object in the routes object as follows

routes:[
    {
      path:"/",
      name:'name',
      component:Home
    },
    {
      path:"/about",
      name:'about',
      component:About
    }
Copy the code

Later in app.vue you can write the to property in router-link so that static links become dynamic links

 <router-link :to="{name:'home'}"> | home page < / router - the link > < the router - link: to ="{name:'about'}"> about < / router - the link >Copy the code

Dynamic Route Matching

For example, create user route user/1 user/2

1. In the index file of the router, follow the path of the route with /: ID

routes:[
    {
      path:"/user/:id",
      name:'user',
      component:User
    }
Copy the code

2. Add params to router-link’s to property in app. vue

Ps: Params is a complex number, so object storage is used

    <router-link :to="{name:'user',params:{id:1}}"1 > user < / router - the link > | < the router - link: to ="{name:'user',params:{id:2}}"2 > user < / router - the link > |Copy the code

3.1 Watch monitoring in user. vue in View

In watch, the $router has a callback function and two properties: to and from which component to go and from which component to come from

exportDefault {// When route parameters change such as /1 to /2 the original component instance will be reused // because two routes render the same component reuse efficiencycreated(){
      console.log(this.$route.params.id); }, watch: {//to go to where from from where$route:(to,from)=>{ console.log(to.params.id); console.log(from.params.id); // Initiate Ajax request backend interface data data-driven view}},}Copy the code

3.2 The route guard beforeRouteUpdate can also be used

BeforeRouteUpdate (to,from,next){console.log(to.params.id); beforeRouteUpdate(to,from,next){console.log(to.params.id); console.log(from.params.id); // Next must be called otherwise it will block the route. }Copy the code

Route matching priority

If you want to go to a page that doesn’t exist, for example, if you want to go to a page that doesn’t exist

Add a routing component with path:’*’ to routes in the router

routes:[
    {
      path:The '*',
      component:() => import('@/views/404')}]Copy the code

This is the local component loading method

Ps: This component should be placed at the bottom of all routing components

A path can match multiple routes. The matching priorities are in the order of route definition. Whichever route component is in the upper part is matched

How do I match wildcards in routes

Suppose the routes component in the router has a path containing wildcards such as

routes:[
    {
      path:'/user-*',
      component:() => import('@/views/User-admin')},]Copy the code

Content that you want to obtain wildcards can be obtained in the corresponding view in this case user-admin

<template> <div> <h3>User-admin page </h3> <! -- Match the wildcard route in /user-* --> <h4>{{$route.params.pathMatch}}</h4>
  </div>
</template>
Copy the code

Use pathMatch in $route.params to retrieve the contents of wildcards in the path

Route Query parameters

Such as how to access http://localhost:8080/page? Id =1&title= ID &title in foo

1. Add a route to the routes in index of the router

    {
      path:'/page',
      name:'page',
      component:() => import('@/views/Page')}Copy the code

2. Add a router-link to app. vue

Ps: The parameter corresponds not to params but to query

<router-link :to="{name:'page',query:{id:1,title:'foo'}}">page</router-link>
Copy the code

3. A Page route can be created using this.$route.query

created () {
      // console.log(this.$route);
      const {id,title} = this.$route.query;
      console.log(id,title); //1, foo
    },
Copy the code

H5 mode vs. historical mode

The route defaults to H5 mode and the site will have # signs such as http://localhost:8080/#/about switching to history will remove # signs to make the site look cleanerhttp://localhost:8080/about

Method: Write mode: ‘history’ in the router index route object

exportDefault new VueRouter({//h5 is the default modeIf the # sign is changed to history mode, there is no # sign
  mode:'history',
  routes:[]
)}
Copy the code

Route redirection and alias

redirect

You can use redirection if you want to type/to automatically redirect to the /home page

Redirect Writes routes in the index of the router to a route component defined by redirect

2. Redirect :{name: destination route name}

The following code

routes:[
    {
      path:'/',
      // redirect: '/home'
      redirect:{name:'home'}
    },
    {
      path:"/home",
      name:'home',
      component:Home
    },
]
Copy the code

The alias

Add alias to the routing component :’ Other remembered pathnames’

Add an alias to the /page route

    {
      path:'/page',
      name:'page',
      component:() => import('@/views/Page'),
      alias: '/aaa'// Alias the route},Copy the code

A subsequent visit to/AAA also brings up the Page page

Routing components pass values

If you want to use $route.params to obtain parameters, there are other problems that can be solved using props

Add props:true to routes :(route) => ({… })

Note that the parentheses are added to the method

    {
      path:"/user/:id",
      name:'user',
      component:User,
      // props:true
      props:(route) => ({
        id:route.params.id,
        title:route.query.title
      })
    }
Copy the code

Next, in the script in user.vue, throw props:[Name of the value to pass]

export default {
    props:['id'.'title'],}Copy the code

Finally, in the template template directly with {{target value name}}

<template> <div> <h3> I am the user {{$routePage. Params. Id}} < / h3 > < h3 > I am a user {{id}} - {{title}} page < / h3 > < / div > < / template >Copy the code

Programmatic navigation

Using router-link in app.vue is life-style navigation. For example, using router-link in app.vue is life-style navigation. Using router-link in app.vue is life-style navigation

1. First add button add a click property to bind a method

2. Write the method in Method

There are several ways to jump

3.1 This.$router. Push (‘ destination path ‘)
$router. Push (‘ destination name ‘)
3.3 this.$router.push({destination route component information}) (can be a path or name and can add params and query attributes)
<template>
  <div>
    <button @click='goHome'</button> < button@click ='goBack'</button> </div> </template>export default {
    methods: {
      goBack() {/ /$router0 means refresh 1 means forward -(?) Step back? This page.$router.go(-1);
      }, 
      goHome() {// programmatic navigation // this.$router.push('/home');

        // this.$router.push('name');

        this.$router.push({
          path:'/'
        });

        // this.$router.push({
        //   name:'user', // params:{id:2} // }); }}},Copy the code

Embedded routines by

Suppose you want to add two child routes with different structures to the User route

1. Add the children attribute [{child route component},{child route component}] to the routes component corresponding to the router index.

Here we add the profile and posts subroutes

 {
    path:"/user/:id",
    name:'user',
    component:User,
    // props:true
    props:(route) => ({
      id:route.params.id,
      title:route.query.title
    }),
    children:[
      {
        path:'profile',
        component:() => import('@/views/Profile')
      },
      {
        path: 'posts',
        component: () => import('@/views/Posts')}}]Copy the code

2. Write Posts. Vue and profile.vue

3. Add a router-link to app. vue

<! -- child link --> <router-link to='/user/1/profile'>user/1/profile</router-link>|
    <router-link to='/user/1/posts'>user/1/posts</router-link>
Copy the code

4. Add a route outlet in User of the parent route

<template> <div> <h3> I am the user {{$routePage. Params. Id}} < / h3 > < h3 > I am a user {{id}} - {{title}} page < / h3 > < button @ click ='goHome'</button> < button@click ='goBack'</button> <! <router-view></router-view> </div> </template>Copy the code

Named view

Loading multiple components

The first component is the default name of defalut. Then write the names of other components and import them asynchronously

{
      path:"/home",
      name:'home',// Component :Home Components :{default:Home,// Default name main:() => import()'@/views/Main'),
        sideBar: () => import('@/views/SideBar')}}Copy the code

2. Create Main and SideBar files

3. Render route exits in app. vue

<! -- Home --> <router-view></router-view> <router-view name='main' class='main'></router-view>
    <router-view name='sideBar' class='sideBar'></router-view>
Copy the code