Dynamic property binding with vue router-link

Dynamic property binding with vue router-link

·

2 min read

<router-link> is a component for enabling page navigation in a router-enabled Vue application. It renders <a> HTML element with the correct href configuration. But the router-link has lots of other advantages when compared with the <a> HTML element

But I faced a small problem with the component when this was configured with the dynamic property configuration. My requirement was to navigate to a details page with the id as the dynamically configured property in the router setting. So my configuration is as the following,

//router/index.js
{
  path: "/products/:id",
  name: "ProductDetail",
  component: () => import("../views/ProductDetail.vue"),
  props: true
},
<router-link
  :to="{name: 'ProductDetail', params: { id: pinned.id }}"
>
  {{ pinned.title }}
</router-link>

Here, id is the dynamic property that will be changed dynamically in the address bar whenever the user clicked on a specific product from the product gallery. Now, this id is used to fetch the product details from the server using the dynamic property.

The setup() function and UI template rendering are happening at the same time due to the async behavior of the Vue framework. So, the params configuration mentioned above in the <router-link> is broken. My application was also stopped working with the following error in the console, image.png

After I did some research about the problem and went through the rendering workflow, I fixed the problem with a simple tweak in my code. I introduced a v-if condition for the property of id. This solved my problem. It gave me clarity that, why the conditional property was required to remove the race condition of UI rendering. So the new code looks like the below,

<router-link
  v-if="pinned.id"
  :to="{name: 'ProductDetail', params: { id: pinned.id }}"
>
  {{ pinned.title }}
</router-link>

I believe that this article helped you by some means. Please keep me supporting and share this with your friends.

Happy coding!

Did you find this article valuable?

Support Tham by becoming a sponsor. Any amount is appreciated!