Vue.js 中获取路由的方法有:1. 使用 $router 属性;2. 使用 useRoute 钩子;3. 通过 props 传递。修改路由可以用 push 或 replace 方法。
如何获取 Vue.js 中的路由
获取 Vue.js 中的路由有几种方法:
1. 使用 $router 属性
created() { console.log(this.$router.currentRoute); // 打印当前路由 }
2. 使用 useRoute 钩子
立即学习“前端免费学习笔记(深入)”;
import { useRoute } from 'vue-router'; const MyComponent = { setup() { const route = useRoute(); console.log(route.path); // 打印当前路由路径 } };
3. 通过 props 传递
在父组件中:
<MyComponent :route="this.$router.currentRoute" />
在子组件中:
props: ['route'], created() { console.log(this.route); // 打印当前路由 }
获取特定路由信息
// 获取当前路由路径 this.$router.currentRoute.path // 获取当前路由名称 this.$router.currentRoute.name // 获取所有路由参数 this.$router.currentRoute.params // 获取单个路由参数 this.$router.currentRoute.params.myParam
修改路由
要修改路由,可以使用 push 或 replace 方法:
this.$router.push({ path: '/new-route' }); // 或 this.$router.replace({ path: '/new-route' });
以上就是vue怎么获取路由的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号