Vue路由参数在函数类型上不存在。

huangapple go评论59阅读模式
英文:

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 -->

&lt;script lang=&quot;ts&quot;&gt;
  import { defineComponent } from &#39;vue&#39;;
  import { useRoute } from &#39;vue-router&#39;;

  export default defineComponent({
    setup() {
      const route = useRoute();

      return {
        route,
      };
    },
    name: &#39;ErrorPage&#39;,
    data() {
      return {
        errorCode: this.route.params.errorCode,
      };
    },
  });
&lt;/script&gt;

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: &quot;error/:errorCode&quot;,
   component: ErroComponent,
   name: &quot;TheErrorRoute&quot;
},
/** ... **/

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.

huangapple
  • 本文由 发表于 2023年5月17日 21:21:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76272585.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定