Javascript 在 VueJS 中访问 $route.params

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47414918/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:50:56  来源:igfitidea点击:

Accessing $route.params in VueJS

javascriptvue.jsroutesrouter

提问by Ian Buss

Looking through this documentation: https://router.vuejs.org/en/essentials/navigation.html

查看此文档:https: //router.vuejs.org/en/essentials/navigation.html

It looks like you can bind the <router-link :to="variableName">Link Text</routerlink>Which is pretty nifty; however, I've had some trouble trying to access route parameters inside of a component I'm trying to build.

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

So I use this:

所以我用这个:

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

To then direct the router view to pull the forum thread. Using this in the router:

然后直接路由器视图拉论坛线程。在路由器中使用它:

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

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

I can see in the forumthread component that $route.params.id is being passed too it; however, when I try to access it like this:

我可以在 forumthread 组件中看到 $route.params.id 也被传递了它;但是,当我尝试像这样访问它时:

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

It's unable to find the params portion of the object.

它无法找到对象的 params 部分。

VueJS is pretty new to me as well as JavaScript itself. All the examples I've seen show the templates being inline with the router file which is something I am trying to prevent to help keep my code readable and clean.

VueJS 和 JavaScript 本身一样,对我来说都很新。我看到的所有示例都显示模板与路由器文件内联,这是我试图阻止的事情,以帮助保持我的代码可读和干净。

What adjustments can I make so that I can pass properties to the template file?

我可以进行哪些调整以便将属性传递给模板文件?

Thanks!

谢谢!

回答by Alex MacArthur

If you're using the Vue Loader setup (which has <template></template>tags in the files), you need to use thisto reference the $router, if you're doing so within the <script></script>part of the file.

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

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