typescriptvuejs3vue-composition-apivue-router4

How to databind the to attribute of vue router's routerlink with Typescript using composition API in Vue 3?


Here is my component:

<script setup lang="ts">
defineProps({
  linkPath: //what should I type here?,
  label: String,
  icon: String
})
</script>

<template>
    <RouterLink :to="linkPath">
      <font-awesome-icon :icon="icon" size="2xl" /> <span class="hidden">{{ label }}</span>
    </RouterLink>
</template>

From the error that I'm getting when hovering over the :to attribute, I can tell that I need the RouteLocationRaw data type to be fed into the attribute but I can't figure out how to do this. Also, assuming that I managed to hook this databinding correctly, how do I pass in the data to the props? I'm assuming it won't be as simple as just typing in the destination route. I'm quite new to Typescript and Vue js.

I tried importing the RouteLocationRaw from vue-router and set it as my linkPath prop's type but VS Code is telling me that I'm using it as a value instead of the type of the props.

Am I supposed to do router.push() on the parent component instead?


Solution

  • There are a few things that you need to update here.

    First, linkPath can be type String but here you need to specify that it is a required prop (required:true) so that typescript knows that it is never undefined which is specified in the error as well.

    enter image description here

    [Optional] Second, you need to save the reference of defineProps() to a const to be able to use it in your template.

    Updated Code

    <script setup lang="ts">
    import { RouterLink } from 'vue-router'
    const props = defineProps({ linkPath: { type: String, required: true } })
    </script>
    <template>
      <div class="about">
        <h1>This is a test page</h1>
        <!-- Both of the following ways work -->
        <RouterLink :to="linkPath">Link to something</RouterLink>
        <RouterLink :to="props.linkPath">Link to something</RouterLink>
      </div>
    </template>