Home > Web Front-end > Vue.js > body text

Detailed explanation of the routing function in Vue3: application to implement routing jump of SPA application

WBOY
Release: 2023-06-18 14:44:58
Original
1312 people have browsed it

With the continuous development of front-end technology, Single Page Application (SPA) has become the mainstream of front-end development, and routing is an integral part of SPA applications. In Vue3, the routing function has been updated and improved, making it easier to use and more powerful. This article will introduce in detail the application of routing functions in Vue3 and how to implement routing jumps in SPA applications.

1. Routing function in Vue3

Routing jumps in Vue3 are all completed through the routing function, which is called the "Route Navigation Function". The basic usage is as follows:

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: '/home',
      component: Home
    },
    {
      path: '/about',
      component: About
    },
    {
      path: '/contact',
      component: Contact
    }
  ]
})

router.push('/home')
Copy after login

Route jump can be achieved by calling the router.push() function to specify the path to be jumped. Among them, the createRouter() function is used to create a router, the history parameter specifies the routing mode, and the routes parameter defines the mapping relationship between routing paths and components.

2. Implement route guard

In actual development, we sometimes need to limit and control route jumps. At this time, we can use the route guard (Route Guard) provided in Vue3. A route guard is a function that is called when a route is about to jump. We can judge and process in this function to achieve routing control. Vue3 provides the following route guard functions:

2.1 beforeEach

This function will be called before each route jump. Returning true means continuing to jump, returning false means canceling. Jump. We can perform login verification, permission judgment and other operations in this function.

router.beforeEach((to, from, next) => {
  // to: 即将要跳转的路由
  // from: 当前页面正要离开的路由
  // next: 控制路由是否可以跳转的函数

  const loggedIn = localStorage.getItem('user')

  if (to.matched.some(record => record.meta.requiresAuth) && !loggedIn) {
    next('/login')
  } else {
    next()
  }
})
Copy after login

2.2 beforeRouteEnter

This function can only be used inside the component. This function is called when the component has not been created yet. We can get the component instance in this function and operate it after getting it.

export default {
  beforeRouteEnter(to, from, next) {
    axios.get('/user').then(response => {
      if (response.data.isAdmin) {
        next()
      } else {
        next('/403')
      }
    })
  }
}
Copy after login

2.3 beforeRouteUpdate

This function is called after the route jumps, but when the current component is still being reused. We can update the component's data in this function.

export default {
  beforeRouteUpdate(to, from, next) {
    const id = to.params.id
    axios.get(`/user/${id}`).then(response => {
      this.user = response.data
      next()
    })
  }
}
Copy after login

3. Implement dynamic routing

Sometimes we need to dynamically generate routing paths when routing jumps. Vue3 provides the "Dynamic Route" function. Dynamic routing is implemented by adding placeholders to the routing path. The placeholders start with ":".

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: '/user/:id',
      component: User
    }
  ]
})
Copy after login

In the above example, we achieved dynamic generation of routing paths through the ":id" placeholder. When routing jumps, we can get the id value in the path through to.params.id.

router.push({ path: `/user/${userId}` })
Copy after login

4. Implement nested routing

For complex pages, we sometimes need to implement nested routing. Vue3 also provides support for nested routing. We can implement nested routing by defining sub-routes in parent routes and sub-routes.

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: '/home',
      component: Home,
      children: [
        {
          path: 'list',
          component: List
        },
        {
          path: 'detail/:id',
          component: Detail
        }
      ]
    }
  ]
})
Copy after login

In the above example, we defined two sub-routes, list and detail, in the home route. In the List component, we can obtain sub-route information through the children attribute of the $route object.

export default {
  created() {
    console.log(this.$route.children) // [ { path: 'list', ... }, { path: 'detail/:id', ... } ]
  }
}
Copy after login

5. Summary

In Vue3, the routing function is one of the keys to implementing SPA applications. Through routing functions, we can implement routing jumps, routing guards, dynamic routing, nested routing and other functions. For developers, mastering the use of routing functions is a very important step, and it is also the only way to improve front-end development capabilities.

The above is the detailed content of Detailed explanation of the routing function in Vue3: application to implement routing jump of SPA application. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template