在VueJS中访问$route.params

46

浏览这份文档:https://router.vuejs.org/zh/guide/essentials/navigation.html

看起来你可以绑定 <router-link :to="variableName">Link Text</router-link>,非常巧妙;但是,在我尝试构建一个组件时,我遇到了一些访问路由参数的问题。

所以我使用了这个:

<router-link :to="permalink">Title of thing</router-link>

然后,使用以下路由器将路由器视图指向拉取论坛线程:

import ForumThread from './views/groupTitle/forumThreadSingle';

// Other routes...
let routes = [
    {
        path: '/groupTitle/th/:id',
        component: ForumThread,
    } 
]; 

我可以看到在论坛主题组件中$route.params.id被传递给它; 然而,当我尝试像这样访问它时:

console.log('The id is: ' + $route.params.id);

无法找到对象的参数部分。

对我来说,VueJS以及JavaScript本身都是比较新的东西。我看到的所有例子都显示模板与路由器文件内联,这是我试图避免的,以帮助保持代码的可读性和清洁度。

我该如何进行调整以便将属性传递到模板文件中呢?

谢谢!


你能展示一下 console.log 语句的更多上下文吗?它是在 Vue 实例的函数中吗? - thanksd
permalink 变量的内容是什么? - awnton
2
在 Vue 组件中,您可以简单地使用 this.$route.params...。 - Thomas
2个回答

89

如果您正在使用Vue Loader设置(其中文件中有<template></template>标签),则需要在文件的<script></script>部分内使用this来引用$router。

 console.log('The id is: ' + this.$route.params.id);

2
在我的情况下,我必须使用console.log('The id is: ' + this.$route.params.id.toString()); - Victor.Uduak

32

对于想要在Vue 3中使用组合式API获取vue-router 4.x参数的人,可以使用useRoute来实现。

import {useRoute} from "vue-router";
setup(){
   const route = useRoute();
   const id = route.params.id;
} 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接