vue3 most complete routing tutorial

Posted by Gulsaes on Sat, 05 Mar 2022 18:03:08 +0100

Introduction to routing. I've released the basic use of vue2 before. You can go there if you want to know vue2 routing tutorial

Let's start routing

Know Vue router

At present, the three popular front-end frameworks have their own routing implementation:

  • ngRouter of Angular
  • ReactRouter of React
  • Vue router of Vue
    Vue router is based on Routing and components
  • Routing is used to set access paths and map paths to components
  • In the single page application of Vue router, the change of page path is the switching of components

Install Vue Router: npm install vue-router@4

Use steps of routing

Basic usage process of routing

// history mode
import {
    createRouter,
    createWebHashHistory,
} from 'vue-router'

import Home from '../pages/Home.vue'
import About from '../pages/About.vue'

const routes = [
// Default path for routing
    {
        path:'/',
        redirect:"/home"
    },
    {
        path: '/home',
        component: Home
    },
    {
        path: '/about',
        component: About
    },
]

// Create routing object
const router = createRouter({
    history: createWebHashHistory(),
    routes
})
export default router;

main.js

import {
    createApp
} from 'vue'
import App from './App.vue'
import router from './router'
createApp(App).use(router).mount('#app')

App.vue

<template>
  <div>
    <router-link to="/home">home</router-link>
    <router-link to="/about">about</router-link>
    <keep-alive>
      <router-view></router-view>
    </keep-alive>
  </div>
</template>

<script>
export default {
  name: "App",
  components: {},
};
</script>

<style>
</style>

router-link

Router link has been mentioned above. Let's briefly introduce its use
Router link actually has many properties that can be configured:

  1. to attribute: is a string or an object
  2. Replace attribute: if the replace attribute is set, router will be called when clicked Replace() instead of router push();
  3. Active class attribute: sets the class applied after activating the a element. The default is router link active
  4. Exact active class attribute: when the link is accurately activated, the < a > class applied to rendering is router link exact active by default;

Route lazy loading

If we can divide the components corresponding to different routes into different code blocks, and then load the corresponding components when the route is accessed, this will
More efficient;

The subcontracting knowledge of webpack can be used here, and Vue Router supports dynamic import of components by default

  1. This is because the component can pass in a component or receive a function, which needs to be put back into a Promise;

  2. The import function returns a Promise;

    const routes = [{
    path: '/',
    redirect: "/home"
    },
    {
    path: '/home',
    component: () => import('.../pages/Home.vue')
    },
    {
    path: '/about',
    component: () => import('.../pages/About.vue')
    },
    ]

We will find that subcontracting does not have a very clear name. In fact, webpack starts from 3 X starts to support the naming of subcontracting (chunk name):

Dynamic routing basic matching

Many times, we need to map the routes of a given matching pattern to the same component:

  1. In Vue Router, we can use a dynamic field in the path, which we call path parameter

    {
    path: "/user/:id",
    component: () => import('.../pages/user.vue')
    }

Jump in router as follows:

<router-link to="/user/123">user</router-link>

Gets the value of the route
In setup, we need to use a hook useRoute provided by Vue router library;

<template>
  <div>{{ route.params }}</div>
</template>

<script>
import { useRoute } from "vue-router";
export default {
  setup() {
    const route = useRoute();

    return { route };
  },
};
</script>

<style lang="scss" scoped>
</style>

NotFound

For routes that are not matched, we usually match to a fixed page

  • For example, in the error page of NotFound, we can write a dynamic route to match all pages at this time;
{
        path: '/:pathMatch(.*)',
        component: () => import('../pages/NotFound.vue')
    }

We can use $route params. Pathmatch gets the passed in parameters:

{{ $route.params.pathMatch }}

Match rule plus*
*I added another one after /: pathMatch(. *);

{
        path: '/:pathMatch(.*)*',
        component: () => import('../pages/NotFound.vue')
    }

Nesting of routes

As the name suggests, it is a sub route, and there is an interface in the interface

   {
        path: '/home',
        component: () => import( /* webpackChunkName:"home-chunk"*/ '../pages/Home.vue'),
        children: [{
            path:'',
            redirect:'/home/product'
        },{
            path:'product',
            component:()=>import('../pages/HomeProduct.vue')
        }]
    },

Page Jump of code

query mode parameters

setup() {
    const router = useRouter();
    const jumpTo = () => {
      router.push({
        path: "/about",
        query: {
          name: "fuck",
        },
      });
    };
    return {jumpTo};
  },

In the interface, click $route Query to get parameters:

 {{$route.query}}

Replace current location

The feature of using push is to press in a new page, so when the user clicks back, the previous page can also go back, but if we want the current
If a page is a replacement operation, you can use replace:

<router-link to="/home/product" replace="">Sub interface</router-link>

Page forward and backward

v-slot of router link

In Vue router3 When x, the router link has a tag attribute, which can determine what elements the router link is rendered into:

  1. But in Vue router 4 Starting with X, the attribute is removed;
  2. It provides us with a more flexible way of v-slot to customize the rendered content;

We use v-slot to scope the slot to get the value passed to us internally:

  1. href: URL after parsing;

  2. Route: the normalized route object after parsing;

  3. navigate: the function that triggers navigation;

  4. isActive: whether to match the status of;

  5. isExactActive: whether it is an accurate matching state;

    <!-- props: href Jump link -->
    <!-- props: route object -->
    <!-- props: navigate Navigation function -->
    <!-- props: isActive Is it currently active -->
    <!-- props: isExactActive Is it currently precisely active -->
    <router-link to="/home" v-slot="props">
      <p @click="props.navigate">{{ props.href }}</p>
      <span :class="{ active: props.isActive }">{{ props.isActive }}</span>
      <span :class="{ active: props.isActive }">{{ props.isExactActive }}</span>
    </router-link>
    

v-slot of router view

Router view also provides us with a slot that can be used for and components to wrap your routing components:

  • Component: the component to render;

  • Route: the parsed standardized route object;

Dynamically add routes

In some cases, we may need to add routes dynamically:
If we are adding a children route to the route, we can pass in the corresponding name:

// Create routing object
const router = createRouter({
    history: createWebHashHistory(),
    routes
})
const categoryA = { //Interface returns routing information
    path: '/category',
    name: 'category',
    component: () => category
};
router.addRoute("category", {
    path: '/child',
    name: 'child',
    component: () => import('../newpage/child.vue')
})

Dynamically delete route

There are three ways to delete a route:
Method 1: add a route with the same name;
Method 2: pass in the name of the route through the removeRoute method;
Method 3: callback through the return value of addRoute method;

Route navigation guard

The navigation guard provided by Vue router is mainly used to guard the navigation by jumping or canceling.
The global front guard beforeEach will be called back when the navigation is triggered:
It has two parameters: to: the Route object to be entered; from: the Route object to leave;
It has a return value: false: cancel the current navigation; Do not return or undefined: default navigation;
Return a routing address: it can be a path of string type; It can be an object, which contains path, query, params and other information;
Optional third parameter: next
In Vue2, we decide how to jump through the next function;
However, in Vue3, we control it through the return value. We no longer recommend using the next function, because it is easy to call next multiple times in development;

Login guard function

router.beforeEach((to, from) => {
    console.log('to', to)
    console.log('from', from)
    if (to.path !== '/about') {
        const token = localStorage.setItem('token', 'qwer')
        if (!token) {
            return '/about'
        }
    }
})

Topics: Front-end css3 html css