[Vuejs]-Vue router linking external websites

0👍

You can do smth like:

[
 {stuff..., "URL":"https://www.google.com/", "external" : true},
 {stuff..., "URL":"/internal-link", "external": false}
]

And then in vue component

<div class="mobile-link" v-for="link in json" :key="link.id">
<a v-if="link.external" :href="link.url">{{ link.Name }]</a>
<router-link v-else :to="link.Url">{{link.Name}}</router-link>
</div>

If you can’t edit your Array directly, use map function with regex ^(http|https)://.

0👍

As shown in your JSON, you could use a regex to determine if the URL is local or external.

So, something like

<a v-if="/https?:\/\//.test(link.Url)" href="link.Url"></a>
<router-link v-else :to="link.Url">{{link.Name}}</router-link>

Ofc, creating a component that encupsulates this condition will be cleaner. 😀

Here is an interesting blog post on how to achieve it. It’s talking about Nuxt.js but it’s basically the same if you only want it for Vue only.
https://lihbr.com/blog/one-link-component-to-rule-them-all

Leave a comment