Home > Article > Web Front-end > How to get jump path parameters in vue
When performing routing jumps in Vue, parameters often need to be passed. So how to get the parameters passed in the target page? This article will introduce how to obtain jump path parameters in Vue.
There are two ways to jump routes in Vue: use the vue-router plug-in or use window.location.href directly in the page to jump. Either way, the method of obtaining jump path parameters is similar.
vue-router is the official routing plug-in provided by Vue, which can help us control routing in Vue. In vue-router, the current route information, including jump path parameters, can be obtained through the $route object.
Suppose we have a routing configuration as follows:
{ path: '/detail/:id', component: Detail }
The :id here indicates that this is a path parameter that can be passed through routing. For example, /detail/123 represents the details with id 123 Page.
In the target page Detail, we can get the passed parameters through $route.params. The code is as follows:
export default { name: 'Detail', mounted() { const id = this.$route.params.id; // 获取跳转路径参数id的值 console.log('id:', id); } };
In the mounted hook, the id parameter passed in the jump path can be obtained through this.$route.params.id.
In Vue, we can also use window.location.href directly for page jump. For example:
window.location.href = '/detail?id=123';
Here we splice the id parameter into the jump url. Let’s see how to get this parameter in the target page.
We can use location.search to get the parameter part after the question mark in the jump path, and then use regular matching to get the value of the parameter we need. The code is as follows:
export default { name: 'Detail', mounted() { const query = location.search.substring(1); // 获取跳转路径参数字符串,去掉问号 const reg = new RegExp(`(^|&)id=([^&]*)(&|$)`); // 匹配id参数的正则表达式 const id = query.match(reg)[2]; // 获取跳转路径参数id的值 console.log('id:', id); } };
The above code matches the value of the id parameter through regular expressions and stores it in the variable id.
The method to obtain jump path parameters in Vue is very simple. Whether using the vue-router plug-in or directly using window.location.href to jump, we can rely on $ route or location objects to obtain the passed parameters. This article introduces two methods. Developers can choose the method that suits them according to the actual situation.
The above is the detailed content of How to get jump path parameters in vue. For more information, please follow other related articles on the PHP Chinese website!