【问题标题】:How to access routing parameters in Vue.js - Nuxt - TypeScript application?如何在 Vue.js - Nuxt - TypeScript 应用程序中访问路由参数?
【发布时间】:2018-07-01 09:00:24
【问题描述】:

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

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

【问题讨论】:

  • 我试过了,但它抛出了一个错误:错误 TS2339: Property '$route' does not exist on type 'default'。

标签: javascript typescript vue.js nuxt.js


【解决方案1】:

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

我认为其他解决方案需要您 augment the Vue module,类似于您找到的 here in the Vue docs

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

【讨论】:

  • 是的,一旦我导入了 vue-router,它就开始工作了,但我不明白为什么会这样 :) 为什么 Nuxt 没有在内部导入它?为什么它在模板部分工作而不导入?
  • 没有进一步调查......我的猜测是它正在修补 Vue 类定义,类似于 Vue 模块步骤的增强。
【解决方案2】:

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

{{ $nuxt.$route.name }}

【讨论】:

  • 你能告诉我如何定义$nuxt吗?我在尝试您的解决方案时收到 $nuxt' is not defined 错误。
【解决方案3】:

我能够通过 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。所以杰森的回答也是有效的

【讨论】:

    猜你喜欢
    • 2021-05-20
    • 2020-01-01
    • 2020-04-09
    • 2021-04-11
    • 2020-07-04
    • 1970-01-01
    • 2021-08-30
    • 2021-02-01
    • 2019-03-02
    相关资源
    最近更新 更多