DEV Community

Cover image for Handle API driven content links in Nuxt js
Liam Hall
Liam Hall

Posted on • Originally published at Medium

Handle API driven content links in Nuxt js

The problem

Internal links in Nuxt are are handled via the nuxt-link component (<nuxt-link>, <n-link>, <NuxtLink>, <NLink>). Not only does the nuxt-link component provide navigation between page components it also enhances performance with smart prefetching. However when pulling page content from an API, we are unable to wrap our links with the nuxt-link component.

Exploring the issue

I spent some time exploring the issue, searching for how I could instruct Nuxt to re-evaluate internal links but to no avail. Eventually I settled on intercepting my API output, adding an onclick to all internal links that would prevent the default link behaviour and instead use Nuxt’s router push function:

<a 
    href="/some/internal/link
    onclick="event.preventDefault(); window.$nuxt._router.push(this.getAttribute(\'href\'))"
>
    Link text
</a>
Enter fullscreen mode Exit fullscreen mode

This did work but it didn’t feel right, so I decided to take to Twitter to ask if anyone else had experience in solving this issue:

Not long later I had a reply from a developer called Alex Lichter, a member of the core Nuxt JS team who pointed me in the direction of Nuxt Interpolation:

What is Nuxt interpolation?

Nuxt interpolation is a module by Dalibor Gogic for binding links to catch the click event, In catching the click event, Nuxt Interpolation with determine whether the link is internal or external. If the link is internal, the link will be handled by Nuxt’s router push method. Nuxt Interpolation is will also determine any links where the target is _blank and add rel="noopener” for improved security.

How to use Nuxt interpolation?

To use Nuxt Interpolation in your Nuxt App, first you’ll need to open your terminal and change directory to the root of your Nuxt App, upon doing so, install Nuxt Interpolation via NPM:

npm i nuxt-interpolation
Enter fullscreen mode Exit fullscreen mode

Once the dependancy is installed, you’ll need to open your nuxt.config.js file and add nuxt-interpolation to the modules array:

{
  modules: [
    ['nuxt-interpolation']
  ]
}
Enter fullscreen mode Exit fullscreen mode

Once you’ve added nuxt-interpolation to your modules array, you’ll be able to the directive in your app. To use nuxt-interpolation simply add the v-interpolation directive to any element you’d like nuxt-interpolation to take effect:

<div v-interpolation v-html="content" />
Enter fullscreen mode Exit fullscreen mode

Conclusion

Nuxt interpolation is a fantastic module for handling API driven content links, it’s very simple to install and use and I’ll be using it not just this current project but in future projects as well, I’m sure.
If you’ve found this article useful, please give it a clap and follow me on Medium, Dev.to and/ or Twitter.

Latest comments (0)