How to use named routes in Vue Router?
In Vue.js, Vue Router is an officially provided routing manager that can be used to build single-page applications. Vue Router allows developers to define routes and map them to specific components to control jumps and navigation between pages. Named routing is one of the very useful features. It allows us to specify a name in the route definition, and then jump to the corresponding route through the name, making route jumping more convenient. In this article, we will learn how to use named routes in Vue Router.
To use named routing, first we need to give each route a name in the routing definition. The following code example shows a Vue Router configuration with two named routes:
import Vue from 'vue'; import VueRouter from 'vue-router'; Vue.use(VueRouter); const routes = [ { path: '/', name: 'home', component: Home }, { path: '/about', name: 'about', component: About } ]; const router = new VueRouter({ routes }); export default router;
In the above code, theroutes
array contains two routing objects, namely the homepage route and About page routing. Thename
attribute is used to specify the name of each route.
Now we can use named routes in components to jump. Vue Router provides$router
objects and$route
objects, through which we can implement routing jumps.
Suppose we have a navigation bar component that contains a link to the About page. We can use therouter-link
component and specify the corresponding route name to implement the jump. The following is a specific code example:
关于
In the above code, we use therouter-link
component in adiv
element andto
The property is set to an object, and thename
property in the object is set to the name of the route we want to jump to (about
in this example).
We can also use thepush
method of the$router
object in JavaScript code to implement routing jumps. The following is an example:
export default { methods: { goToAboutPage() { this.$router.push({ name: 'about' }); } } }
In the above code, we define a method namedgoToAboutPage
in themethods
of the component, and use ## in this method #$router.pushmethod to implement the function of jumping to the about page.
$router.pushmethod or the
router-linkcomponent. Using named routing will bring better development experience and code maintainability.
The above is the detailed content of How to use named routes in Vue Router?. For more information, please follow other related articles on the PHP Chinese website!