如何访问 Vue.js - Nuxt - TypeScript 应用程序中的路由参数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48386513/
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-10-21 05:11:18  来源:igfitidea点击:

How to access routing parameters in Vue.js - Nuxt - TypeScript application?

javascripttypescriptvue.jsnuxt.js

提问by Andrew Bogdanov

I'm building a website that is based on Nuxt TypeScript Startertemplate. I've created a dynamically routed page _id.vue inside of my pages folder and I want to have access to that id property inside of my TS class. I can access it in my template by writing {{$route.params.id}}but when I try to reference $routeinside of the class I get an error:

我正在构建一个基于Nuxt TypeScript Starter模板的网站。我在我的 pages 文件夹中创建了一个动态路由页面 _id.vue 并且我想访问我的 TS 类中的 id 属性。我可以通过编写在模板中访问它,{{$route.params.id}}但是当我尝试$route在类内部进行引用时,出现错误:

error TS2304: Cannot find name '$route'.

错误 TS2304:找不到名称“$route”。

回答by Jason Awbrey

As a simple solution, try importing route from vue-router, like this:

作为一个简单的解决方案,尝试从 vue-router 导入路由,如下所示:

<script lang="ts">
import Component from "vue-class-component"
import { Route } from "vue-router"

@Component({})
export default class RoutingExample extends Vue {
    created() {
        console.log(this.$route) // this should not throw TS errors now
    }

}
</script>

Other solutions I think would require you to augment the Vue module, something similar to what you'd find here in the Vue docs.

我认为其他解决方案需要您扩充 Vue 模块,类似于您在 Vue 文档中找到的内容。

More Vue + TypeScript examples can be found in this repo: https://github.com/jsonberry/vue-typescript-examples

更多 Vue + TypeScript 示例可以在这个 repo 中找到:https: //github.com/jsonberry/vue-typescript-examples

回答by ozo

better and the right solution for nuxtjs project to find current page URL or param just use

nuxtjs 项目找到当前页面 URL 或参数的更好和正确的解决方案,只需使用

{{ $nuxt.$route.name }}

回答by Andrew Bogdanov

I was able to access route.params via fetch function, taking params from the context object that is passed to this function by default:

我能够通过 fetch 函数访问 route.params,从默认情况下传递给此函数的上下文对象中获取参数:

<script lang="ts">
import Component from "nuxt-class-component"
@Component({})
export default class RoutingExample extends Vue {
    fetch ({ store, params }) {
       console.log("params:", params.id);
       ...
    }
}
</script>

but the caveat is that params would only be available in that fetch hook, not in other hooks such as created or mounted. So Jason answer is also valid

但需要注意的是,params 仅在该 fetch 钩子中可用,而不能在其他钩子(例如 created 或 mount)中使用。所以杰森的回答也是有效的