英文:
Vue route params does not exist on type function
问题
以下是已经翻译好的内容:
我正在尝试从我的 Vue 页面中的路由获取一些参数,所以我有以下代码:
<script lang="ts">
  import { defineComponent } from 'vue';
  import { useRoute } from 'vue-router';
  export default defineComponent({
    setup() {
      const route = useRoute();
      return {
        route,
      };
    },
    name: 'ErrorPage',
    data() {
      return {
        errorCode: this.route.params.errorCode,
      };
    },
  });
</script>
但我的编译器报错如下:
> 属性 'params' 在类型 'Function' 上不存在。
有办法让这个工作吗?
我还尝试过在没有 setup 的情况下使用 `this.$route.params.errorCode`,但是得到了相同的错误。
英文:
I'm trying to get some params from my route in a vue page so I have the following:
<!-- language: lang-html -->
<script lang="ts">
  import { defineComponent } from 'vue';
  import { useRoute } from 'vue-router';
  export default defineComponent({
    setup() {
      const route = useRoute();
      return {
        route,
      };
    },
    name: 'ErrorPage',
    data() {
      return {
        errorCode: this.route.params.errorCode,
      };
    },
  });
</script>
but my compiler is failing with the error
>Property 'params' does not exist on type 'Function'.
Is there a way to make this work?
I have also tried using this.$route.params.errorCode without the setup, but get the same error
答案1
得分: 1
useRoute 函数返回的 route 对象上直接有一个 params 属性,您可以使用它来访问您 URL 中的参数。
// ErrorComponent.vue
/* ... */
setup() {
  const route = useRoute();
  
  const errorCode = ref(route.params.errorCode);  
  return {
    route,
    errorCode
  };
},
/** ... **/
另外,请确保在您的路由配置中正确定义了该参数:
// router.js
/** ... **/
{
   path: "error/:errorCode",
   component: ErroComponent,
   name: "TheErrorRoute"
},
/** ... **/
顺便提一下,您应该避免在单个组件中混合使用组合式 API 和选项 API。我的回答基于您想要使用组合式 API。
英文:
There is a params property directly on the route object that it returned by the useRoute function. You can use that to access the params in your url.
// ErrorComponent.vue
/* ... */
setup() {
  const route = useRoute();
  
  const errorCode = ref(route.params.errorCode);  
  return {
    route,
    errorCode
  };
},
/** ... **/
Also, make sure that the parameter is correctly defined in your router config:
// router.js
/** ... **/
{
   path: "error/:errorCode",
   component: ErroComponent,
   name: "TheErrorRoute"
},
/** ... **/
As a side note, you should avoid mixing the composition API and the options API, in a single component. My answer considers that you want to use the composition API.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论