Vue Routing Guide: A map for navigating single-page applications (Vue Router and <router-view>)

Front-end development engineer (main job), technical blogger (side job), passed CET6
Ashan and her cat_CSDN personal homepage
Senior topic writer at Niuke, creating a high-quality column “Essentials for Front-end Interviews” at Niuke
The contracted author of Lanqiao Cloud Class, the front-end and back-end practical courses “Vue.js and Egg.js Develop Enterprise-level Health Management Projects” and “Take you to fully master uni-app from entry to practice” have been launched on Lanqiao Cloud Class

Article directory

  • I. Introduction
    • Understand the concepts and benefits of Single Page Applications (SPA)
    • The role of Vue Router and ``
  • II. Basic use
    • Install and configure Vue Router
    • Create routes and define routing tables
    • Use `` in templates to display matching components

I. Introduction

Understand the concepts and advantages of Single Page Applications (SPA)

When it comes to web applications, there are two main types: multi-page applications (MPA) and single-page applications (SPA).

Multi-page applications are a traditional form of web application in which a new page is loaded from the server every time the user interacts with the application. Each page is a complete HTML document, containing its own styles, scripts and content. When the user navigates to a different page, the entire page reloads.

In contrast, asingle-page application is an application built on a single page that does not reloadwhen the user interacts with the application. Instead, only the data and resources needed by the application are obtained from the server through asynchronous requests. When the user switches navigation, only specific parts of the page are dynamically updated, while other page elements remain unchanged.

Advantages of single-page applications include:

  1. Faster interactive experience
  2. Reduce server load
  3. Better code organization and maintenance
  4. Cross-platform capabilities
  5. Support offline access

In summary, single-page applications bring many advantages to modern web applications by providing a faster interactive experience, reduced server load, better code organization and maintenance, cross-platform capabilities, and offline access support. As a developer, understanding the concepts and benefits of SPA can help you make better technology choices and design decisions.

The role of Vue Router and

Vue Router is a routing manager officially provided by Vue.js for building single-page applications (SPA). It is tightly integrated with the Vue.js framework, providing navigation and routing capabilities to the application.

The main function of Vue Router is to implement page navigation and component routing of the application. It manages the display of different views and components through URL-based navigation, and can dynamically update page content based on user interactions.

Specifically, the following are the main functions of Vue Router:

  1. Route mapping: Vue Router allows you to define routing tables in your application, mapping URL paths to corresponding components. Through routing configuration, you can define the component display corresponding to each URL, and automatically load and render the corresponding components during page navigation.

  2. Nested routing: Vue Router supports nested routing, allowing you to create a hierarchical page structure in your application. By nesting routes, you can use in the component of the parent route to display the content of multiple child routes on the same page.

  3. Route parameter passing: Vue Router allows you to pass parameters between routes, including path parameters, query parameters or state parameters. This allows you to pass data between different pages to customize page presentation and functionality.

  4. Navigation Guard: Vue Router provides navigation guard function, allowing you to execute logic before and after routing switching. You can use navigation guards to control access to routes, handle operations such as user authorization and authentication, and perform some additional asynchronous operations when switching routes.

  5. Named views: Vue Router supports named views, allowing multiple to be used in the same parent route to display different named views. This allows you to display different components on the same page at the same time, achieving more flexible layouts and complex page structures.

is one of the key components provided by Vue Router. Its function is to occupy a place in the Vue component and be used to render matching routing components. When the URL changes, Vue Router will find the matching component based on the routing configuration and render it to for display.

In general, Vue Router provides powerful routing management functions in Vue.js single-page applications, including route mapping, nested routing, route parameter passing, navigation guards, named views, etc., and is a placeholder for rendering different routing components in the component. These features make building complex page navigation and component routing easier and more efficient.

II. Basic usage

Install and configure Vue Router

To install and configure Vue Router, you can follow these steps:

  1. Install Vue Router: Use npm or yarn to install Vue Router in the terminal. You need to execute the following command in the root directory of the Vue project:

    npm install vue-router
    # or
    yarn add vue-router
    
  2. Create a routing configuration: Create a new file in your project, usually named router.js or router/index.js, as the routing configuration file.

    // router.js or router/index.js
    
    import Vue from 'vue';
    import VueRouter from 'vue-router';
    
    //Import your component
    import Home from './views/Home.vue';
    import About from './views/About.vue';
    
    Vue.use(VueRouter);
    
    const routes = [
      {<!-- -->
        path: '/',
        name: 'home',
        component:Home
      },
      {<!-- -->
        path: '/about',
        name: 'about',
        component: About
      }
    ];
    
    const router = new VueRouter({<!-- -->
      mode: 'history', // You can choose 'hash' or 'history' mode
      routes
    });
    
    export default router;
    

    In the above code example, we first import Vue and VueRouter, and use Vue.use() to install the Vue Router plug-in. Then, we define the routing table routes, where each route object contains path (path), name (name) and component (component) field. Finally, we create a new VueRouter instance, configure the routing mode (you can choose hash or history mode) and routing table, and finally export the instance.

  3. Use routing configuration in the main entry file: Find your main entry file (usually main.js), and import and use the routing configuration file.

    // main.js
    
    import Vue from 'vue';
    import App from './App.vue';
    import router from './router';
    
    new Vue({<!-- -->
      router,
      render: h => h(App)
    }).$mount('#app');
    

    In the above code example, we imported the routing configuration file we created earlier and passed it to the router option of the Vue instance. This way, Vue Router can be used to manage navigation and routing within the application.

  4. Use in the component: Find the component template that needs to display the routing component, and add the component at the appropriate location.

    <!-- App.vue or other component templates -->
    
    <template>
      <div id="app">
        <!-- Other component contents -->
        <router-view></router-view>
      </div>
    </template>
    

    The component will be used to dynamically render the matching routing component and display it at that location.

  5. Add navigation links: Add components where needed to create navigation links.

    <!-- Header.vue or other component templates -->
    
    <template>
      <header>
        <nav>
          <router-link to="/">Home</router-link>
          <router-link to="/about">About</router-link>
        </nav>
      </header>
    </template>
    

    The component is used to render a tag. It will generate the correct link based on the configured to attribute to implement routing. Navigation between.

  6. Run the application: After completing the above steps, you can run your Vue application and use Vue Router to implement page navigation and routing functions.

The above are the basic steps to install and configure Vue Router. You can adjust and extend it based on your project needs and routing configuration. The detailed Vue Router documentation can provide more information about configuration and functional options. You can refer to the official documentation: Vue Router.

Create routes and define routing tables

To create routes and define routing tables, you can follow these steps:

  1. Create a new file in your Vue project, usually named router.js or router/index.js, as the routing configuration file.

  2. Import Vue, VueRouter, and use Vue.use(VueRouter) to install the Vue Router plug-in. Make sure you have Vue Router installed in your project.

    // router.js or router/index.js
    
    import Vue from 'vue';
    import VueRouter from 'vue-router';
    
    Vue.use(VueRouter);
    
  3. Import your component. According to your project structure and requirements, import the components needed for routing into the routing configuration file.

    // router.js or router/index.js
    
    import Home from './views/Home.vue';
    import About from './views/About.vue';
    
  4. Define routing table routes. In the routes array, each route object contains path (path), name (name) and component ( component) field.

    // router.js or router/index.js
    
    const routes = [
      {<!-- -->
        path: '/',
        name: 'home',
        component:Home
      },
      {<!-- -->
        path: '/about',
        name: 'about',
        component: About
      }
    ];
    

    In the above example, we defined two routes: one is the Home component corresponding to the root path /, and the other is the /about path corresponding The About component. You can define more routes based on your project needs.

  5. Create a new VueRouter instance and pass it the route table. You can also choose the routing mode, which can be ‘hash’ mode or ‘history’ mode.

    // router.js or router/index.js
    
    const router = new VueRouter({<!-- -->
      mode: 'history',
      routes
    });
    

    In this example, we use the history’ mode, which removes the #’ symbol from the URL, making the URL more user-friendly and semantic.

  6. Export the created routing instance for use in the main entry file.

    // router.js or router/index.js
    
    export default router;
    

After completing the above steps, you have completed the process of creating routes and defining routing tables. You can add, modify, or delete routes according to project needs, and specify the corresponding components for each route. Remember to import and use the routing instance in the main entry file to enable routing functionality in your application.

In your Vue component, you render matching route components via the component and create navigation links using the component. For example, use the component in your App.vue component:

<!-- App.vue or other component templates -->

<template>
  <div id="app">
    <!-- Other component contents -->
    <router-view></router-view>
  </div>
</template>

In this way, according to the current routing path, Vue Router will render the matching routing component to for display.

You can customize more routing configurations as needed, such as adding nested routing, routing parameters, and navigation guards. Vue Router’s documentation provides more detailed configuration and function descriptions. You can refer to the official documentation: Vue Router.

Use in the template to display matching components

It’s very simple to use in a template to display matching components. Just insert the tag into your template.

Assuming that you have followed the previous steps to create routes and define routing tables, let me now explain how to use in a template.

<!-- App.vue or other component templates -->

<template>
  <div id="app">
    <!-- Other component contents -->
    <router-view></router-view>
  </div>
</template>

In the above code, we have inserted the tag in the template. When using Vue Router to navigate to a matching route, the component of the corresponding route will be rendered and displayed at the location of .

For example, the component corresponding to the /home route is defined in the routing table as Home. When you access the /home path, Home The component will be rendered and displayed in .

As your route matches different paths, the content in will be dynamically updated based on the current route, displaying the corresponding component content.

It should be noted that is a route view slot, which is responsible for rendering matching components, so you only need to define one in the template. You can place it in the appropriate location based on the needs of your application.