What is routing in Vue.js? How to use routing?

What is routing in Vue.js? How to use routing?

In Vue.js, routing refers to the mechanism that provides different page content or views for different URL addresses. Routing in Vue.js can be implemented using the Vue Router library, which is a routing management library officially provided by Vue.js.

insert image description here

Introduction to Vue Router

Vue Router is the official routing management library provided by Vue.js, which can help us realize the routing function in single page application (SPA). Vue Router allows us to define routes in URLs and display different views or components according to different URL addresses. Using Vue Router in Vue.js allows us to better manage the state and user interface of the application and improve the interactivity of the application.

Install and configure Vue Router

To use Vue Router, we need to install it first. You can use npm or yarn to install Vue Router, the command is as follows:

npm install vue-router

# 或者

yarn add vue-router

Once installed, we need to configure Vue Router in our Vue.js application. A Vue Router instance can be created before the Vue.js instance is created and passed as an option to the Vue.js constructor.

Here's a simple Vue.js application that uses Vue Router to define routes:

import Vue from 'vue';
import VueRouter from 'vue-router';
import Home from './components/Home.vue';
import About from './components/About.vue';

Vue.use(VueRouter);

const routes = [
  {
    
    
    path: '/',
    component: Home,
  },
  {
    
    
    path: '/about',
    component: About,
  },
];

const router = new VueRouter({
    
    
  mode: 'history',
  routes,
});

const app = new Vue({
    
    
  router,
}).$mount('#app');

In the code above, we first import Vueand VueRouter, and call Vue.use(VueRouter)to install the Vue Router plugin. Then, we defined two routes, corresponding to /and /aboutthese two URL addresses. Each route specifies a component, Homethe and Aboutcomponents respectively. Finally, we create a Vue Router instance and pass it as an option to the Vue.js constructor. In the Vue.js instance, we mount the created Vue Router instance on routerthe option .

In the code above, we also specified modethe option as 'history'. This is the option to specify Vue Router to use HTML5 history mode. In HTML5 history mode, Vue Router will use the browser's history API to implement routing. This allows us to change the URL and update the view without refreshing the page.

Create routing components

In Vue.js, a route component refers to a view or component corresponding to a route. When a user visits a specific URL address, Vue Router will display the corresponding routing component according to the URL address. In Vue.js, we can use normal Vue components as routing components. To use a component as a routing component, just specify the component in the routing configuration.

Here is an example of a simple routing component:

// Home.vue
<template>
  <div>
    <h1>这是主页</h1>
  </div>
</template>
// About.vue
<template>
  <div>
    <h1>这是关于页面</h1>
  </div>
</template>

In the above code, we created Home.vueand About.vuetwo components respectively, and used them as routing components.

define routes

In Vue.js, we can use Vue Router to define routes. Routing is composed of multiple routing records, and each routing record is an object that contains URL addresses and corresponding components.

We can VueRouteruse routesthe option of to define routes. routesThe option is an array, and each element in the array is a route record object, which contains pathand componenttwo properties.

const routes = [
  {
    
    
    path: '/',
    component: Home,
  },
  {
    
    
    path: '/about',
    component: About,
  },
];

In the above code, we defined two routing records, corresponding to /and /aboutthe two URL addresses respectively. pathThe attribute specifies the URL address, and componentthe attribute specifies the corresponding component.

In Vue Router, route records can be organized using nested routes. Nested routing refers to nesting multiple sub-routing records in a routing record. Nested routes can help us better organize and manage routes and improve the maintainability of the application.

Here is an example of nested routes:

const routes = [
  {
    
    
    path: '/',
    component: Home,
  },
  {
    
    
    path: '/about',
    component: About,
    children: [
      {
    
    
        path: '',
        component: AboutHome,
      },
      {
    
    
        path: 'history',
        component: AboutHistory,
      },
      {
    
    
        path: 'team',
        component: AboutTeam,
      },
    ],
  },
];

In the above code, we define a nested route, and Aboutthe route record contains three child route records. pathThe attributes of the child route record are relative to paththe attribute of the parent route record.

render route

In Vue.js, we can use <router-view>component to render routes. <router-view>The component is a component provided by Vue Router, which dynamically renders the corresponding routing component according to the current URL address.

Here's a simple Vue.js template that uses <router-view>the component to render routes:

<template>
  <div id="app">
    <router-view></router-view>
  </div>
</template>

In the code above, we used <router-view>the component to render the route. When a user visits a specific URL address, Vue Router will dynamically render the corresponding routing component according to the URL address, and render the component into <router-view>the component .

route navigation

In Vue.js, route navigation refers to the process of switching between different routes for the user. Routing navigation can be implemented in two ways: programmatic navigation and declarative navigation.

programmatic navigation

In Vue.js, we can use $routerobjects for programmatic navigation. $routerThe object is the routing object provided by Vue Router, which contains some methods and properties that can help us navigate routing.

Here's an example of a simple programmatic navigation:

// 在组件中进行导航
this.$router.push('/about');

// 在路由守卫中进行导航
router.beforeEach((to, from, next) => {
    
    
  // 判断是否需要进行登录验证
  if (to.meta.requiresAuth && !isLogin) {
    
    
    next('/login');
  } else {
    
    
    next();
  }
});

In the code above, we use $router.push()the method for programmatic navigation. $router.push()The method will modify the URL address of the browser to the specified URL address, and dynamically load the corresponding routing component.

In addition, in the routing guard, we can also perform programmatic navigation. Routing guards refer to some hook functions triggered during routing navigation, which can help us realize the control and management of routing navigation.

Declarative Navigation

In Vue.js, we can also use <router-link>components for declarative navigation. <router-link>The component is a component provided by Vue Router, which can convert the user's click event into routing navigation and help us realize the shortcut of routing navigation.

Here's a simple declarative navigation example:

<router-link to="/about">关于我们</router-link>

In the code above, we use <router-link>the component for declarative navigation. toThe attribute specifies the URL address to be navigated to, and <router-link>the component will convert the click event into route navigation, and automatically modify the URL address of the browser.

routing parameters

In Vue.js, we can use route parameters to pass data. Routing parameters refer to the parameters contained in the URL address, which can be used to pass data to routing components.

In Vue Router, we can use :the symbol to define route parameters. The syntax for defining route parameters is as follows:

const router = new VueRouter({
    
    
  routes: [
    {
    
    
      path: '/user/:id',
      component: User,
    },
  ],
});

In the above code, we use :the symbol to define the routing parameter, idwhich is the name of the parameter. When the user visits /user/123this URL address, Vue Router will 123pass it as a parameter value to the routing component.

In the routing component, we can access the routing parameters through $route.paramsthe attribute . $route.paramsProperties is an object that contains all the parameters of the current route.

Here is an example of a simple route parameter:

// User.vue
<template>
  <div>
    <h1>用户信息</h1>
    <p>用户 ID{
    
    {
    
     $route.params.id }}</p>
  </div>
</template>

In the code above, we use $route.params.idto access route parameters. When the user accesses /user/123this URL address, the routing component will display 用户 ID:123the text.

Routing hook function

In Vue.js, routing hook functions refer to some functions triggered during routing navigation. The routing hook function can help us realize the control and management of routing navigation, and can be triggered at multiple moments such as before routing navigation, after routing navigation, before routing component activation, and after routing component activation.

In Vue Router, routing hook functions can be divided into two types: global hook functions and component hook functions. A global hook function refers to a hook function that is triggered during the entire route navigation process, and a component hook function refers to a hook function that is triggered in a specific route component.

The following are some commonly used routing hook functions:

global hook function

  • beforeEach: Triggered before route navigation, used to control and manage route navigation.
  • beforeResolve: Triggered before the routing component is activated, used for asynchronous data loading and processing.
  • afterEach: Triggered after route navigation, used for subsequent processing of route navigation.

Component hook function

  • beforeRouteEnter: Triggered before the routing component is activated, used to initialize the routing component and load data.
  • beforeRouteUpdate: Triggered when the current routing component is updated, used to handle changes in routing parameters.
  • beforeRouteLeave: Triggered when the routing component leaves, used to clean up the routing component and save data.

Here is an example of a simple global hook function:

// router.js
const router = new VueRouter({
    
    
  routes: [...],
});

router.beforeEach((to, from, next) => {
    
    
  // 判断是否需要进行登录验证
  if (to.meta.requiresAuth && !isLogin) {
    
    
    next('/login');
  } else {
    
    
    next();
  }
});

In the above code, we use the beforeEachglobal hook function to control the route navigation. Before routing navigation, we judge whether the current route needs to perform login verification, and check whether the user has logged in. If the user is not logged in and the current route requires login verification, jump to the login page; otherwise, continue routing navigation.

Summarize

Vue Router is the official routing manager provided by Vue.js, which can help us realize the routing navigation of single-page applications. Vue Router provides a variety of routing navigation methods, including declarative navigation and programmatic navigation. In Vue Router, we can use routing parameters to pass data, and use routing hook functions to control and manage routing navigation. By learning and using Vue Router, we can more easily manage and control the routing navigation of single-page applications.

Guess you like

Origin blog.csdn.net/it_xushixiong/article/details/131012457