Vue.js 中获取路由的方法有:1. 使用 $router 属性;2. 使用 useRoute 钩子;3. 通过 props 传递。修改路由可以用 push 或 replace 方法。

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