Vue Router: Create smooth navigation and routing functions in single-page applications (SPA)

foreword

insert image description here
"Author's Homepage" : Sprite Youbai Bubbles
"Personal Website" : Sprite's personal website
"Recommendation Column" :

Java one-stop service
Front-end cool code sharing
uniapp-from construction to promotion
From 0 to hero, Vue's road to god
Solving algorithm, one column is enough Let's talk about architecture from 0
The subtle way of data circulation

Please add a picture description

introduction

In modern web development, Single Page Application (SPA) has become a popular architectural pattern. By dynamically loading content, SPA achieves an interactive experience without refreshing the entire page, providing a smoother and more responsive user interface.

However, it is not easy to realize the navigation and routing functions of SPA. This is where Vue Router comes into play. As the official routing manager provided by Vue.js, Vue Router provides us with a simple and powerful way to manage the navigation and routing of the application.
insert image description here

This article will lead you to learn more about Vue Router and explore its rich features and flexible configuration options. We will start with installation and configuration, and gradually introduce core concepts and technologies such as basic routing, nested routing, routing navigation guards, routing parameters, and routing lazy loading. At the same time, we will also explore how to deal with routing errors and integration state management, and reinforce the knowledge learned through practical examples.

Whether you are a beginner or an experienced developer, this article will provide you with clear guidance and practical sample code. Let's dive into Vue Router and add powerful navigation and routing capabilities to our single page applications!
insert image description here

1 Introduction

What is Vue Router?

Vue Router is the official routing manager provided by Vue.js. It helps developers build single-page applications (SPA) and implement navigation between pages. By using Vue Router, you can define the mapping relationship between different URL paths and corresponding components, so that when the browser address bar changes, the corresponding components can be dynamically loaded and rendered, so as to achieve page refresh switching.

The role and advantages of Vue Router

Vue Router plays an important role in Vue.js applications and has the following functions and advantages:

  • Route management : Vue Router provides a mechanism to manage the routes of the application. You can define routing rules to map URL paths to corresponding components. In this way, when the user enters a specific URL or clicks a link in the browser, Vue Router will automatically load and render the corresponding components to realize page switching.

  • Nested routing : Vue Router supports nested routing, allowing you to define sub-routes inside a component. This way, you can build more complex page structures, split pages into multiple modular components, and combine and nest them through nested routes.

  • Routing parameters : Vue Router allows you to define parameters in the route path to dynamically pass data to components. In this way, you can render different content according to different parameter values, achieving more flexible and personalized page display.

  • Navigation guards : Vue Router provides a navigation guard feature that allows you to perform some custom logic before and after routing switches. You can use navigation guards for authentication, permission control, or other operations to ensure that users have the appropriate conditions and permissions when accessing specific pages.

  • Code splitting : Vue Router supports splitting the application code into multiple small chunks (chunks) on demand and loading them asynchronously when needed. This reduces the initial load time and improves the performance and responsiveness of the application.

In short, Vue Router is a powerful and flexible tool that provides Vue.js developers with rich routing management functions, making it easier and more efficient to build complex front-end applications.
insert image description here

2. Installation and configuration

Install Vue Router

To use Vue Router, you first need to install the Vue Router package in your Vue project. You can install it through npm or yarn.

Use npm:

npm install vue-router

Use yarn:

yarn add vue-router

After the installation is complete, you can introduce Vue Router into the project and start configuring.

Configure Vue Router in Vue project

After installing Vue Router, you need to configure it in your Vue project to use it. Here are the basic steps to configure Vue Router:

  1. Import Vue and Vue Router in the project's entry file (usually main.js), and use Vue.use(VueRouter)to install the Vue Router plugin.
import Vue from 'vue';
import VueRouter from 'vue-router';

Vue.use(VueRouter);
  1. Create routing rules (defining the mapping relationship between URL paths and components). You can define routing rules in a separate file, eg router.js.
import Vue from 'vue';
import VueRouter from 'vue-router';

Vue.use(VueRouter);

const routes = [
  // 路由规则
];

const router = new VueRouter({
    
    
  routes
});

export default router;

In the above code, we created an empty routing rule array routes, and you can add specific routing rules according to actual needs. Then, we created a Vue Router instance and configured routing rules into the instance. Finally, we export defaultexport the router instance for use elsewhere.

  1. Configure the router in the root Vue instance. In the project's entry file (usually main.js), configure the router into the root Vue instance.
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, we created the root Vue instance and configured the router into routerthe options in the instance. In this way, the entire application can use Vue Router for routing management.

Through the above steps, you have successfully installed and configured Vue Router. Now you can start to define specific routing rules and use the functions provided by Vue Router in components.

insert image description here

3. Basic Routing

In web applications, routing refers to determining the mapping between URLs and specific handlers or views. Basic routing is a common routing method when building web applications. The following describes how to create basic routes, route links and route views, and the use of dynamic route parameters.

Create basic routes

In most web frameworks, creating a basic route usually involves several steps:

  1. Import the required library or module, for example in Python you can use the Flask framework.
  2. Create an application instance.
  3. Define routing rules, that is, URL paths and corresponding processing functions or views.
  4. Run the application.

Here is a sample code to create a basic route using the Flask framework:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return 'Hello, World!'

if __name__ == '__main__':
    app.run()

In the above example, @app.route('/')the routing rules for the root path are defined, that is, when the user accesses the root path, home()the function will be called and "Hello, World!" will be returned.

Routing Links and Routing Views

Routing links are used to generate URL links in applications, enabling users to easily navigate to different pages or perform specific operations. In most web frameworks, a specific syntax can be used to generate routing links.

The following is a sample code that uses the Flask framework to generate routing links:

from flask import Flask, url_for

app = Flask(__name__)

@app.route('/')
def home():
    return 'Hello, World!'

@app.route('/about')
def about():
    return 'About page'

if __name__ == '__main__':
    with app.test_request_context():
        print(url_for('home'))  # 输出:/
        print(url_for('about'))  # 输出:/about

In the examples above, url_for()the function is used to generate the URL associated with the specified view function or handler. By calling url_for('home')and url_for('about'), the root path and the URL of the about page can be generated, respectively.

Dynamic Routing Parameters

Dynamic routing parameters allow variable parts to be included in the URL so that actions can be performed based on different input values. In most web frameworks, a specific syntax can be used to define dynamic route parameters.

Here is an example code for defining dynamic routing parameters using the Flask framework:

from flask import Flask

app = Flask(__name__)

@app.route('/user/<username>')
def user_profile(username):
    return f'User profile: {
      
      username}'

if __name__ == '__main__':
    app.run()

In the above example, <username>is a dynamic route parameter that matches any string in the URL and passes it as a parameter to user_profile()the function. For example, when a user visits /user/johndoe, it is called user_profile('johndoe')and returns "User profile: johndoe".

Through the above examples, you can understand how to create basic routes, generate route links, and use dynamic route parameters. Depending on the specific web framework and language, the actual code details may vary, but the fundamentals are similar.

insert image description here

4. Nested routing

In web development, nested routing is a technique for grouping multiple routes together. It allows us to define sub-routes under a main route, thus creating more complex routing structures. Nested routes can be used in various use cases and provide many benefits.

Create nested routes

To create nested routes, we need to define sub-routes under the main route. Child routes are usually associated with parent routes and can be accessed through the path of the URL. Here is an example code snippet showing how to create nested routes:

// 主要路由
const express = require('express');
const app = express();

// 父路由
const parentRouter = express.Router();
app.use('/parent', parentRouter);

// 子路由
const childRouter = express.Router();
parentRouter.use('/child', childRouter);

// 子路由的路由处理函数
childRouter.get('/', (req, res) => {
    
    
  res.send('This is the child route');
});

// 启动服务器
app.listen(3000, () => {
    
    
  console.log('Server is running on port 3000');
});

In the above code, we have created a main route /parentand a child route /parent/child. When accessed /parent/child, the processing function of the child route will be triggered and the corresponding response will be returned.

Usage Scenarios and Benefits of Nested Routes

Nested routes are very useful in many situations, especially when we need to organize complex routing structures. Here are some common usage scenarios and benefits of nested routes:

  1. Modular development : Nested routes allow us to organize related routes together to form a modular code structure. This improves code readability and maintainability, and makes it easier for team members to understand and collaborate on development.

  2. Permission control : By nesting routes, we can implement authentication and permission checks in the parent route, and then place protected sub-routes where authorized access is required. This simplifies the permission control logic and provides more flexible access control policies.

  3. Resource Nesting : Nesting routes can provide a clearer and consistent URL structure when dealing with actions related to a specific resource. For example, in a blogging application, nested routes could be used to handle different actions for resources such as posts, comments, and tags.

  4. Code reuse : By nesting routes, we can share the same child route among multiple parent routes. This avoids repetitive writing of similar routing processing logic and improves code reusability and maintainability.

In conclusion, nested routing is a powerful tool that can help us organize and manage complex routing structures. It provides benefits such as modular development, permission control, resource nesting, and code reuse, making our applications easier to develop and maintain.
insert image description here

5. Route Navigation Guard

A route navigation guard is a function performed during route navigation to control whether a user is allowed to access a specific route or perform a specific action. It can help us implement functions such as authentication, permission checking, and data loading. In front-end frameworks such as Vue.js and Angular, common route navigation guards include global pre-guards, route-exclusive guards, and guards within components.

Global Front Guard

Global pre-guards are guards that are called before route navigation. They apply to all routes throughout the application and can be used to perform some common tasks such as authentication and permission checking. Here's an example code that uses Vue Router's global front guard:

import Vue from 'vue';
import VueRouter from 'vue-router';

Vue.use(VueRouter);

const router = new VueRouter({
    
    
  routes: [
    // 路由配置
  ]
});

router.beforeEach((to, from, next) => {
    
    
  // 在这里执行身份验证和权限检查等任务
  if (to.meta.requiresAuth && !isAuthenticated()) {
    
    
    next('/login');
  } else {
    
    
    next();
  }
});

new Vue({
    
    
  router,
  render: h => h(App)
}).$mount('#app');

In the above example, beforeEachthe method is a global pre-guard that will be called before each route navigation. We can perform tasks such as authentication and permission checks in this guard, and decide whether to allow the user to continue navigating to the target route as needed.

Route exclusive guards

Route-exclusive guards are guards that apply only to a specific route. They are suitable for certain routes that require specific processing logic, such as loading data or performing other operations. The following is a sample code using Vue Router's route exclusive guard:

const router = new VueRouter({
    
    
  routes: [
    {
    
    
      path: '/profile',
      component: Profile,
      beforeEnter: (to, from, next) => {
    
    
        // 在这里执行特定路由的处理逻辑
        if (isProfileComplete()) {
    
    
          next();
        } else {
    
    
          next('/complete-profile');
        }
      }
    },
    // 其他路由配置
  ]
});

In the above example, beforeEnterthe method is a route-exclusive guard, which applies only to /profileroutes. We can execute the processing logic of a specific route in this guard, and decide whether to allow the user to continue navigating to the target route as needed.

Guards within components

In-component guards are guarded functions defined inside the component. They apply to component-specific lifecycle hook functions, such as beforeRouteEnter, , beforeRouteUpdateand beforeRouteLeave. Here's an example code for an in-component guard using Vue Router:

const Profile = {
    
    
  // 组件配置

  beforeRouteEnter(to, from, next) {
    
    
    // 在组件进入路由之前执行的逻辑
    if (isAuthenticated()) {
    
    
      next();
    } else {
    
    
      next('/login');
    }
  },

  beforeRouteUpdate(to, from, next) {
    
    
    // 在组件在当前路由更新时执行的逻辑
    // 可以根据需要执行一些操作
    next();
  },

  beforeRouteLeave(to, from, next) {
    
    
    // 在组件离开当前路由时执行的逻辑
    // 可以根据需要执行一些清理操作
    next();
  }
};

In the above example, we Profiledefined three in-component guards inside the component: beforeRouteEnter, , beforeRouteUpdateand beforeRouteLeave. These guards can perform specific logic at different lifecycle stages of the component, such as authentication before the component enters the route, perform some actions when the component is updated, or perform some cleanup operations when the component leaves the route.

To sum up, route navigation guards are a powerful tool for controlling behavior during route navigation. Global pre-guards apply to all routes in the entire application, route-specific guards apply to specific routes, and component-specific guards apply to lifecycle hook functions of specific components. By using these guards, we can implement functions such as authentication, permission checking, data loading, and control the user's navigation behavior in the application.
insert image description here

6. Routing parameters

In web development, routing parameters refer to a way of passing data to a URL. Common route parameter passing methods include query parameters, route parameters, and named routes.

query parameters

Query parameters are the way to pass data by appending key-value pairs after the question mark in the URL. For example, the following URL contains a query parameter idwhose value is 123:

https://example.com/product?id=123

In the front-end framework, these data can be used by obtaining the query parameters in the URL. Here is an example code snippet demonstrating how to get query parameters using JavaScript:

// 获取URL中的查询参数
const urlParams = new URLSearchParams(window.location.search);

// 获取特定查询参数的值
const productId = urlParams.get('id');

console.log(productId); // 输出:123

routing parameters

Route parameters are a way to pass data as part of the URL. Typically, route parameters are used to identify a resource or specify the content of a particular page. For example, the following URL :idis a route parameter:

https://example.com/product/123

In the front-end framework, routing parameters can be captured and extracted by defining routing rules. Here is an example code snippet demonstrating how to use route parameters in React:

import { BrowserRouter as Router, Route } from 'react-router-dom';

function ProductPage() {
  return (
    <Router>
      <Route path="/product/:id">
        {({ match }) => {
          const { id } = match.params;
          return <div>Product ID: {id}</div>;
        }}
      </Route>
    </Router>
  );
}

In the above code, /product/:ida route with route parameters is defined. When the URL matches the path, React Router will pass the matched parameters to ProductPagethe component, and match.paramsget the value of the parameter through the attribute.

named route

Named routing is to assign a name to a specific routing rule so that it can be referenced and generated URLs in code. Using named routes can improve the maintainability and readability of your code. Different front-end frameworks may have different implementations.

The following is an example code snippet demonstrating how to define and use named routes in Vue.js:

// 定义命名路由
const routes = [
  {
    
    
    path: '/product/:id',
    name: 'product',
    component: ProductPage,
  },
];

// 使用命名路由
const router = new VueRouter({
    
    
  routes,
});

// 在代码中生成URL
const productId = 123;
const productUrl = router.resolve({
    
     name: 'product', params: {
    
     id: productId } }).href;

console.log(productUrl); // 输出:/product/123

In the above code, namewe /product/:iddefined a named route for the route by specifying the attribute in the route rule product. We can then use router.resolve()methods to generate corresponding URLs based on named routes and parameters.

Here are some basic concepts and sample codes about routing parameters. The specific implementation method may vary depending on the front-end framework used, and you can further study and practice according to your own project requirements and framework documents.

insert image description here

7. Route lazy loading

In web applications, lazy loading of routes is an optimization technique that delays loading the code of a page or component to improve the performance and user experience of the application. Through lazy loading, only when the user visits the required page, the code required for the page will be downloaded, instead of loading the code of all pages at once.

The concept and principle of lazy loading

The concept of lazy loading is based on the idea of ​​modular development. In traditional front-end development, the entire application is usually packaged into one or more JavaScript files, and all codes are loaded at once when the application starts. The problem with this is that if the application is very large, the user may have to wait a long time to see the page content.

Lazy loading divides the application into multiple small modules, each module corresponds to a page or component, and then dynamically loads the code of these modules as needed. When a user visits a certain page, only the modules corresponding to the page will be downloaded and executed, and other modules will remain unloaded. This reduces the initial load time and improves the responsiveness of the application.

The principle of lazy loading is to use an asynchronous loading mechanism, such as dynamic import (Dynamic Import) or on-demand loading (Lazy Loading) and other technologies. These techniques allow developers to dynamically load a module's code when needed, rather than loading all the code at once at application startup.

Improve application performance with lazy loading

Using lazy loading can significantly improve the performance and user experience of your application. Here are some advantages of lazy loading:

  1. Reduce initial load time: Only the code required for the current page will be downloaded and executed, reducing initial load time and allowing users to see page content faster.
  2. Reduce resource consumption: The code of unvisited pages or components will not be loaded, reducing the consumption of network bandwidth and browser memory.
  3. Improve the response speed: When the user navigates to other pages, only the modules corresponding to the page need to be loaded, which improves the response speed of the application.
  4. Optimized user experience: Users can interact with the application faster without waiting for all the code to load.

Here is an example code snippet showing how to use lazy loading of routes in React:

import React, { lazy, Suspense } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';

// 懒加载页面组件
const HomePage = lazy(() => import('./pages/HomePage'));
const AboutPage = lazy(() => import('./pages/AboutPage'));
const ContactPage = lazy(() => import('./pages/ContactPage'));

function App() {
  return (
    <Router>
      <Suspense fallback={<div>Loading...</div>}>
        <Switch>
          <Route exact path="/" component={HomePage} />
          <Route path="/about" component={AboutPage} />
          <Route path="/contact" component={ContactPage} />
        </Switch>
      </Suspense>
    </Router>
  );
}

In the above code, lazy()the page components are lazy loaded through the function. When the user visits the corresponding route, the code of the page component will be dynamically loaded. SuspenseThe component is used to display a loading prompt during the loading process to provide a better user experience.
insert image description here

8. Navigation analysis process

Navigation analysis refers to the process of loading the corresponding components on the page according to the user's access path in the front-end routing. The following will introduce the order and process of navigation analysis, as well as the hook function of navigation analysis.

The sequence and process of navigation resolution

  1. The user clicks or enters the URL address.
  2. The browser sends a request to the server.
  3. The server returns an HTML file.
  4. The browser parses the HTML file and builds a DOM tree.
  5. The browser parses the CSS file and renders the page style.
  6. The browser executes JavaScript code.
  7. The front-end routing takes over URL parsing and matches the corresponding routing rules according to the URL path.
  8. According to the routing rules, the corresponding components are loaded and rendered on the page.

Hook function for navigation analysis

In the process of navigation analysis, the front-end framework usually provides some hook functions to execute custom logic at different stages. These hook functions can help us perform some additional operations during the navigation parsing process, such as permission verification, data preloading, etc.

The following is a sample code snippet showing the use of the navigation parsing hook function in Vue.js:

const router = new VueRouter({
    
    
  routes: [
    // 路由配置
  ]
});

router.beforeEach((to, from, next) => {
    
    
  // 在导航解析之前执行的逻辑
  // 可以进行权限验证等操作
  next();
});

router.afterEach((to, from) => {
    
    
  // 在导航解析之后执行的逻辑
  // 可以进行页面统计等操作
});

router.onError((error) => {
    
    
  // 导航解析出错时执行的逻辑
  console.error(error);
});

In the above code, beforeEachthe function will be called before each navigation analysis, we can perform some authorization verification logic in this function, and next()continue the navigation analysis process by calling the function.

afterEachThe function will be called after each navigation analysis, and we can perform some page statistics logic or other operations in this function.

onErrorThe function will be called when there is an error in the navigation parsing, and we can handle the error message in this function.

These hook functions provide flexible extension points, which can execute custom logic at different stages of navigation parsing according to actual needs.
insert image description here

9. Routing Transition Effects

In Vue Router, you can use transition class names to implement routing transition effects. You can animate route transitions by adding appropriate CSS transition class names.

First, define CSS classes for transition effects in your application. For example, you could create a fadeclass called fade-in and fade-out effects:

.fade-enter-active,
.fade-leave-active {
    
    
  transition: opacity 0.5s;
}

.fade-enter,
.fade-leave-to {
    
    
  opacity: 0;
}

Then, in the routing configuration of Vue Router, add transitionattributes for components that require transition effects, and specify the transition class name. For example:

const router = new VueRouter({
    
    
  routes: [
    {
    
    
      path: '/home',
      component: Home,
      meta: {
    
     transition: 'fade' }
    },
    {
    
    
      path: '/about',
      component: About,
      meta: {
    
     transition: 'fade' }
    }
  ]
});

Finally, in the root component of your application, use <transition>the component wrapper <router-view>and meta.transitiondynamically bind the transition class name according to the properties of the current route. For example:

<template>
  <div>
    <transition :name="$route.meta.transition">
      <router-view></router-view>
    </transition>
  </div>
</template>

In this way, when you switch routes in the application, the corresponding transition effect will be applied according to the transition class name specified in the route configuration.
insert image description here

10. Routing Error Handling

In Vue Router, you can handle route error conditions by using routed navigation guards. Specifically, you can use beforeEachnavigation guards to check if a route exists or if the user has sufficient permissions.

First, you can use it in the global navigation guard beforeEachto check if the route exists. For example:

router.beforeEach((to, from, next) => {
    
    
  if (to.matched.length === 0) {
    
    
    // 路由不存在
    next('/404');
  } else {
    
    
    next();
  }
});

In the above example, if the target route does not match any routing configuration, ie to.matched.length === 0, the user is redirected to a custom 404 page.

Additionally, you can use navigation guards in routes that require permission checks to handle insufficient permissions. For example:

const router = new VueRouter({
    
    
  routes: [
    {
    
    
      path: '/admin',
      component: Admin,
      meta: {
    
     requiresAuth: true }
    },
    // ...
  ]
});

router.beforeEach((to, from, next) => {
    
    
  if (to.meta.requiresAuth && !isAuthenticated()) {
    
    
    // 权限不足,用户未登录
    next('/login');
  } else {
    
    
    next();
  }
});

In the example above, if the user tries to access a route that requires authentication /admin, but the user is not logged in ( isAuthenticated()returns false), the user is redirected to the login page.
insert image description here

11. Integration of Routing and State Management

In a Vue.js application, you can integrate Vue Router with the Vuex state management library to better manage the routing and state of the application.

First, make sure you have Vue Router and Vuex installed and properly configured in your application.

Then, in your application's entry file, create a Vuex store instance and integrate it with Vue Router. For example:

import Vue from 'vue';
import Vuex from 'vuex';
import VueRouter from 'vue-router';

Vue.use(Vuex);
Vue.use(VueRouter);

const store = new Vuex.Store({
    
    
  // ...定义你的状态、mutations、actions等
});

const router = new VueRouter({
    
    
  routes: [
    // ...定义你的路由配置
  ]
});

// 在路由导航前,将store实例注入到路由的meta字段中
router.beforeEach((to, from, next) => {
    
    
  to.meta.store = store;
  next();
});

new Vue({
    
    
  router,
  store,
  // ...其他配置项
}).$mount('#app');

Now, you can access the Vuex store instance in the route component and update the state or call actions when the route switches. For example:

export default {
    
    
  computed: {
    
    
    count() {
    
    
      return this.$route.meta.store.state.count;
    }
  },
  methods: {
    
    
    increment() {
    
    
      this.$route.meta.store.commit('increment');
    },
    fetchData() {
    
    
      this.$route.meta.store.dispatch('fetchData');
    }
  }
};

In the above example, we this.$route.meta.storeaccessed the Vuex store instance and used state, commitand dispatchto read state, submit mutations, and dispatch actions.

This way, you can easily use the Vuex state management library in your routing components to manage the state of your application.
insert image description here

12. Use Vue Router to build a complete SPA application example

Below is an example of building a complete Single Page Application (SPA) using Vue Router. We'll create a simple task management application that includes tasks list, task details, and adding tasks.

First, make sure you have Vue.js and Vue Router installed and properly configured in your application.

install dependencies

npm install vue vue-router

Create components

In your application, create the following components:

  • TaskList.vue: A task list component that displays all tasks.
  • TaskDetail.vue: Task details component, which displays detailed information of a single task.
  • AddTask.vue: Add task component, used to add new tasks.

configure routing

In your application's entry file, configure Vue Router and define the routes:

import Vue from 'vue';
import VueRouter from 'vue-router';

import TaskList from './components/TaskList.vue';
import TaskDetail from './components/TaskDetail.vue';
import AddTask from './components/AddTask.vue';

Vue.use(VueRouter);

const routes = [
  {
    
     path: '/', component: TaskList },
  {
    
     path: '/task/:id', component: TaskDetail },
  {
    
     path: '/add-task', component: AddTask }
];

const router = new VueRouter({
    
    
  routes
});

new Vue({
    
    
  router,
  // ...其他配置项
}).$mount('#app');

In the above example, we defined three routes: the root path /corresponds to TaskListthe component, /task/:idthe corresponding TaskDetailcomponent, and the /add-taskcorresponding AddTaskcomponent.

create template

In the root component of your application, create a template and use <router-view>the directive to render the component corresponding to the current route:

<template>
  <div id="app">
    <h1>任务管理应用</h1>
    <router-view></router-view>
  </div>
</template>

perfect components

Next, we need to refine its functionality and styling in each component. Here is just a simple example, you can expand it according to your needs.

TaskList.vue

<template>
  <div>
    <h2>任务列表</h2>
    <ul>
      <li v-for="task in tasks" :key="task.id">
        <router-link :to="'/task/' + task.id">{
   
   { task.title }}</router-link>
      </li>
    </ul>
  </div>
</template>

<script>
export default {
      
      
  data() {
      
      
    return {
      
      
      tasks: [
        {
      
       id: 1, title: '任务1' },
        {
      
       id: 2, title: '任务2' },
        {
      
       id: 3, title: '任务3' }
      ]
    };
  }
};
</script>

TaskDetail.vue

<template>
  <div>
    <h2>任务详情</h2>
    <p>{
   
   { task.title }}</p>
    <p>{
   
   { task.description }}</p>
  </div>
</template>

<script>
export default {
      
      
  data() {
      
      
    return {
      
      
      task: {
      
      }
    };
  },
  created() {
      
      
    // 根据路由参数获取任务详情
    const taskId = this.$route.params.id;
    this.task = this.fetchTask(taskId);
  },
  methods: {
      
      
    fetchTask(id) {
      
      
      // 根据任务ID从服务器获取任务详情的逻辑
      // 返回一个包含任务信息的对象
    }
  }
};
</script>

AddTask.vue

<template>
  <div>
    <h2>添加任务</h2>
    <!-- 添加任务的表单 -->
  </div>
</template>

<script>
export default {
      
      
  methods: {
      
      
    addTask() {
      
      
      // 处理添加任务的逻辑
    }
  }
};
</script>

run the application

Finally, create a file at the root of your application index.htmlthat includes Vue and your entry point:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Vue Router SPA</title>
</head>
<body>
  <div id="app"></div>
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
  <script src="main.js"></script>
</body>
</html>

Now, you can run your application and see the effect.

This example demonstrates how to build a complete SPA application using Vue Router. By defining routes, creating components, and configuring Vue Router, you can easily build applications with multiple pages and navigation. You can extend and customize this example to meet your actual project needs.

insert image description here

13. Summary and advanced

Summary and review of Vue Router

Vue Router is a routing manager officially provided by Vue.js for building single-page applications (SPA). It provides a clean and flexible way to manage the routing of the application and enable navigation and switching between pages.

When using Vue Router, you can map URL paths to corresponding components by defining routing configurations. You can use features such as dynamic route parameters, nested routes, and named views to meet different routing needs. At the same time, Vue Router also provides functions such as navigation guards, routing transition effects, and error handling to enhance the interactivity and user experience of the application.

To summarize the main features and advantages of Vue Router:

  • Ease of use: Vue Router provides a concise API and clear documentation, making routing configuration and use very easy.
  • Responsive routing: Vue Router will automatically respond to URL changes and load corresponding components according to the configured routing rules.
  • Nested routing: Vue Router supports nested routing, allowing you to define sub-routes under a parent route to build complex page structures.
  • Navigation guards: Vue Router provides multiple navigation guards, allowing you to execute custom logic before and after routing switching, such as permission verification, data loading, etc.
  • Routing transition effect: Vue Router supports the transition effect of routing switching through CSS transition class names to improve user experience.
  • Error handling: Vue Router allows you to handle error conditions such as route does not exist or insufficient permissions, and redirect or prompt accordingly.

Further study and explore the advanced features of Vue Router

If you want to further learn and explore the advanced features of Vue Router, here are a few things to consider:

  1. Dynamic route matching : Learn how to use dynamic route parameters to match different URL paths, and get and use these parameters in components.
  2. Naming Routes and Naming Views : Learn how to name your route configuration and views for more flexible route navigation and component rendering.
  3. Programmatic navigation : master how to use programmatic navigation methods to realize page jump and navigation, instead of relying only on declarative routing links.
  4. Routing meta information : Learn how to add meta information in routing configuration, and use these meta information in navigation guards for permission verification and other logical processing.
  5. Lazy Load Routing : Learn how to use lazy loading (asynchronous components) to delay loading of components corresponding to routes, improving application performance and loading speed.
  6. Routing parameter passing : Explore different ways to pass parameters between routes, including query parameters, props passing parameters, and routing state management.
  7. Advanced application of routing transition effects : Learn more about how to use transition class names and dynamic transition effects to achieve more complex routing switching animations.

By learning these advanced features in depth, you will be able to better use Vue Router to build complex single-page applications and provide users with a richer interactive experience.

Guess you like

Origin blog.csdn.net/Why_does_it_work/article/details/131756756