Search code examples
javascriptvue.jsvuejs3vue-routervue-composition-api

Redirect user to an external website using VueJs 3


I built a navigation bar that should redirect users to external social media links.

Here you can see the url I get after I clicked on the GitHub link and the following errors.

enter image description here enter image description here

<template>
  <nav>
    <ul>
      <li v-for="link in links" :key="link">
        <link-atom :to="link.path">
          {{ link.name }}
        </link-atom>
      </li>
    </ul>
  </nav>
</template>

<script setup>
import LinkAtom from "#/atoms/Link.vue";

const links = [
  {
    name: "GitHub",
    path: "https://github.com/",
  },
  {
    name: "LinkedIn",
    path: "https://www.linkedin.com/",
  },
  {
    name: "Dribbble",
    path: "https://dribbble.com/",
  },
];
</script>

<style lang="scss" scoped></style>
<template>
  <component :is="is" :href="href" :to="to">
    <slot></slot>
  </component>
</template>

<script setup>
import { computed } from "vue";

const props = defineProps({
  is: { type: String, default: "router-link" },
  to: { type: [String, Object], required: true },
});

const href = computed(() => {
  if (props.is === "a") return props.to;
  else return null;
});

const to = computed(() => {
  if (props.is === "router-link") return props.to;
  else return null;
});
</script>

If you have any idea to make it work,

Thanks for your help !


Solution

  • Since the paths are external urls you should add the prop is with a as value, then add target="_blank" based on the presence of a :

         <li v-for="link in links" :key="link">
            <link-atom :to="link.path" is="a">
              {{ link.name }}
            </link-atom>
          </li>
    

    in link-atom component :

      <component :is="is" :href="href" :to="to" :target="`${is==='a'?'_blank':''}`">
        <slot></slot>
      </component>