首页 文章

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

提问于
浏览
3

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

error TS2304: Cannot find name '$route'.

2 回答

  • 1

    我能够通过fetch函数访问route.params,从默认情况下传递给此函数的上下文对象中获取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钩子中使用,而不能在其他钩子中使用,例如创建或挂载 . 所以杰森的回答也是有效的

  • 0

    作为一个简单的解决方案,尝试从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示例:https://github.com/jsonberry/vue-typescript-examples

相关问题