Home  >  Article  >  Web Front-end  >  An article that explains Vue routing in detail: vue-router

An article that explains Vue routing in detail: vue-router

青灯夜游
青灯夜游forward
2022-09-01 19:43:191896browse

This article will give you a detailed explanation of Vue Vue-Router in the FamilyBucket and learn about routing knowledge. I hope it will be helpful to everyone!

An article that explains Vue routing in detail: vue-router

The development history of front-end routing

The concept of routing appeared in software engineering and was first implemented in back-end routing , the reason is that the development of the web has mainly gone through the following stages:

  • Back-end routing stage;
  • Front-end and back-end separation stage;
  • Single page rich application (SPA) );

1. Back-end routing stage

Early website development The entire HTML page is rendered by the server, that is The server directly produces and renders the corresponding HTML page and returns it to the client for display. As shown in the picture:

An article that explains Vue routing in detail: vue-router

Advantages: Conducive to SEO optimization

Disadvantages: The entire page is maintained by back-end personnel, and HTMl code and data corresponding logic will be mixed together and written And maintenance is very poor.

2. Front-end and back-end separation

**Front-end rendering:**The static resources involved in each request will be obtained from the static resource server, these resources include HTML CSS JS, and then render the resources returned by these requests on the front end. Every request from the client will request a file from the static resource server. At this time, the backend is just responsible for providing the API.

Separation of front-end and back-end:

  • The back-end is only responsible for providing the API, and the front-end obtains data through Ajax and renders the data to the page through JavaScript
  • The back-end focuses on data, the front-end focuses on interaction and visualization

Single page (SPA) rich application stage:

  • Separate the front-end and back-end A layer of front-end routing is added on the basis of The front-end maintains a set of routing rules
  • Core: Change the page URL, but do not refresh the page.

Get to know vue-router

Install Vue-Router

npm install vue-router

Steps:

  • Create routing components that need to be mapped [Related recommendations: vue video tutorial]

  • Create routing objects through createRouter, and pass in routes and history mode

  • Use app to register routing object (use method)

  • Route usage: through and and

An article that explains Vue routing in detail: vue-router

An article that explains Vue routing in detail: vue-router

import { createRouter, createWebHashHistory } from "vue-router"

import Home from "../views/Home.vue"
import About from "../views/About.vue"
// 创建一个路由:映射关系
const router = new createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: "/",
      redirect: "/home"
    },
    {
      path: "/home",
      component: Home
    },
    {
      path: "/about",
      component: About
    }
  ]
})

export default router

Supplement: Other attributes of the route

name attribute: record the unique name of the route ;

meta attribute: custom data

router-link (supplementary)

router-link actually has many properties that can be configured :

  • to attribute: is a string or an object
  • replace attribute: If the replace attribute is set, when clicked, router.replace() will be called instead. router.push(). Generally, the replace attribute is not used, and the user experience is not very good.
  • active-class attribute: Set the class applied after activating the a element. The default is router-link-active
  • exact-active-class attribute: When the link is accurately activated, it is applied to rendering. class, the default is router-link-exact-active;

Route lazy loading

Problem: When packaging and building applications, the JavaScript package will become very Large, affecting page loading

Solution: Split the components corresponding to different routes into different code blocks, and then load the corresponding components when the route is accessed. It can also improve the efficiency of first-screen rendering. Among them, Vue-Router supports dynamic loading of components by default. Because component can be passed in a component or receive a function, the function needs to put back a Promise. The import function returns a Promise

An article that explains Vue routing in detail: vue-router

Dynamic routing

1. Basics of dynamic routing Match

Maps routes for a given matching pattern to the same component. You can load different routes according to your different needs to achieve different implementations and page renderings.

The use of dynamic routing is generally used in conjunction with role permission control.

For example: There is a User component, which should render to all users, but the user's ID is different. We can do this by using a dynamic field in the path, which we call a path parameter. Then implement the jump in .

An article that explains Vue routing in detail: vue-router

An article that explains Vue routing in detail: vue-router

2. 获取动态路由的值

获取动态路由的值(例如上面例子中 用户id 123),在template中,直接通过 $route.params获取值。

  • 在created中,通过 this.$route.params获取值
  • 在setup中,我们要使用 vue-router库给我们提供的一个hook useRoute

An article that explains Vue routing in detail: vue-router

3. NotFound

对于没有匹配到相应的路由,我们可以给用户匹配一个固定的页面。通过 $route.params.pathMatch获取到传入的参数

An article that explains Vue routing in detail: vue-router

路由的嵌套

组件的本身也有组件需要内部切换,这个时候就可以采用嵌套路由,在第一层路由中也使用router-view来占位之后需要渲染的组件。

An article that explains Vue routing in detail: vue-router

{
      path: "/home",
      component: () => import("../views/Home.vue"),
      children: [
        {
          path: "/show",
          component: () => import("../views/component/show.vue")
        },
        {
          path: "/detail",
          component: () => import("../views/component/detail.vue")
        }
      ]
    },

编程式导航

1. 代码的页面跳转

通过代码来控制页面的跳转

栗子:点击一个按钮跳转页面

An article that explains Vue routing in detail: vue-router

2. query 方式的参数

通过query的方式来传递参数,在界面中通过 $route.query 来获取参数。

An article that explains Vue routing in detail: vue-router

3. 替换当前的位置

使用push的特点是压入一个新的页面,那么在用户点击返回时,上一个页面还可以回退,但是如果我们希望当前页面是一个替换 操作,那么可以使用replace。这个时候已经不能回退了。

4. 页面的前后跳转

  • router 的 go 方法(指定向前(向后)跳转几步)

  • router 的back 方法 (回溯历史,向后一步)

  • router 的forward 方法(历史中前进,向前一步)

动态添加路由

场景:根据用户的不同权限,注册不同的路由

An article that explains Vue routing in detail: vue-router

补充:路由的其他方法

删除路由有以下三种方式:

  • 方式一:添加一个name相同的路由;
  • 方式二:通过removeRoute方法,传入路由的名称;
  • 方式三:通过addRoute方法的返回值回调;

router.hasRoute():检查路由是否存在。

router.getRoutes():获取一个包含所有路由记录的数组。

路由导航守卫

vue-router 提供的导航守卫主要用来通过跳转或取消的方式守卫导航

全局的前置守卫==beforeEach==是在导航触发时会被回调的,它有两个参数:

  • to:即将进入的路由Route对象;
  • from:即将离开的路由Route对象;

返回值:

  • false:取消当前导航;
  • 不返回或者undefined:进行默认导航;
  • 返回一个路由地址:可以是一个String类型的路径也可以是一个对象

An article that explains Vue routing in detail: vue-router

1. 登录守卫功能

场景:只有登录了的用户才能看到的页面

An article that explains Vue routing in detail: vue-router

2. 其他导航守卫

Vue还提供了很多的其他守卫函数,目的都是在某一个时刻给予回调,可以更好的控制程序的流程或者功能

[导航守卫](导航守卫 | Vue Router (vuejs.org))

流程:

  • 导航被触发。

  • 在失活的组件里调用 beforeRouteLeave 守卫。

  • 调用全局的 beforeEach 守卫。

  • 在重用的组件里调用 beforeRouteUpdate 守卫(2.2+)。

  • 在路由配置里调用 beforeEnter。  解析异步路由组件。

  • 在被激活的组件里调用 beforeRouteEnter。

  • Call the global beforeResolve guard (2.5).

  • Navigation confirmed.

  • Call the global afterEach hook.

  • Trigger DOM update.

  • Call the callback function passed to next in the beforeRouteEnter guard, and the created component instance will be passed in as a parameter of the callback function.

For more programming-related knowledge, please visit: Introduction to Programming! !

The above is the detailed content of An article that explains Vue routing in detail: vue-router. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete