Home > Article > Web Front-end > How to use routing to pass and receive parameters in Vue?
How to use routing to pass and receive parameters in Vue?
Vue is a popular JavaScript framework for building modern, responsive web applications. In Vue, routing is an important concept, which is used to manage navigation and jumps between web pages. During the development process, we often need to pass data between different routes. This article will introduce how to use routing to pass and receive parameters in Vue, and provide corresponding code examples.
1.1 Query parameters
Query parameters are parameters in the routing URL, in the form of ?key=value. We can use the query attribute of the $route object to get the passed parameters. The following is an example of using query parameters to pass parameters:
In the sender route, we can use the $route.router.push method to jump to the receiver route and pass the parameters:
this.$router.push({ path: '/receiver', query: { name: 'John', age: 25 } });
In the receiver route, we can use $route.router.query to get the passed parameters:
console.log(this.$route.query.name); // John console.log(this.$route.query.age); // 25
1.2 Dynamic routing
Dynamic routing uses parameters as part of the URL, in the form /:param. We can use $route.params to get the passed parameters. The following is an example of using dynamic routing to pass parameters:
In the sender route, we can use the $route.router.push method to jump to the receiver route and pass the parameters:
this.$router.push({ path: `/receiver/${this.name}/${this.age}` });
In the receiver route, we can use $route.params to get the passed parameters:
console.log(this.$route.params.name); // John console.log(this.$route.params.age); // 25
<template> <div> <h1>Welcome to the receiver page!</h1> <p>Name: {{ name }}</p> <p>Age: {{ age }}</p> </div> </template> <script> export default { data() { return { name: '', age: '' } }, mounted() { this.name = this.$route.query.name; this.age = this.$route.query.age; // 或者 this.name = this.$route.params.name; // this.age = this.$route.params.age; } }; </script>
The above example shows how to use the $route object in the receiver component to obtain the query parameters or dynamic parameters passed by the route. We assign the passed parameters to the data attribute of the component for use in the template.
Summary
It is very simple to use routing to pass parameters and receive parameters in Vue. Through query parameters or dynamic routing, we can pass data between routes and have it processed and used in the receiver component. Whether it is query parameters or dynamic routing, the passed parameters can be obtained through the $route object. I hope this article can help you better understand and use the routing parameter passing function in Vue.
The above is the detailed content of How to use routing to pass and receive parameters in Vue?. For more information, please follow other related articles on the PHP Chinese website!