繁体   English   中英

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

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

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

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

作为一个简单的解决方案,尝试从 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>

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

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

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

{{ $nuxt.$route.name }}

我能够通过 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>

但需要注意的是,params 只能在该 fetch 挂钩中使用,而不能在其他挂钩中使用,例如 created 或mounted。 所以杰森的回答也是有效的

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM