// 在 Vue 组件中获取当前页面路由的示例代码
// 1. 使用 this.$route 获取当前路由信息
export default {
mounted() {
// 当组件挂载时,获取当前路由信息
console.log(this.$route);
// 获取当前路由的路径
console.log(this.$route.path);
// 获取当前路由的名称
console.log(this.$route.name);
// 获取当前路由的参数
console.log(this.$route.params);
// 获取当前路由的查询参数
console.log(this.$route.query);
}
}
// 2. 使用 watch 监听路由变化
export default {
watch: {
$route(to, from) {
// 当路由发生变化时触发
console.log('新路由:', to);
console.log('旧路由:', from);
}
}
}
this.$route:这是 Vue Router 提供的一个属性,可以在任何 Vue 组件中使用。它包含了当前路由的所有信息,例如路径、参数、查询字符串等。
this.$route.path:获取当前路由的路径(URL 路径部分)。
this.$route.name:获取当前路由的名称(如果定义了名称的话)。
this.$route.params:获取动态路由参数。例如,对于 /user/:id 这样的路由,params 会包含 { id: '123' }。
this.$route.query:获取 URL 中的查询参数。例如,对于 /user?id=123,query 会包含 { id: '123' }。
watch: { $route(to, from) {...} }:监听 $route 的变化,当用户导航到新路由时触发回调函数,可以用于在路由变化时执行某些操作。
上一篇:vue router.push
下一篇:vue修饰符
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站