Home > Software engineering >  Redirect user to an external website using VueJs 3
Redirect user to an external website using VueJs 3

Time:10-10

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 !

CodePudding user response:

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>

CodePudding user response:

If you want to have links to external websites, I suggest you use anchor tag instead of router-link.

In your custom link-atom you don't pass the is prop, and you set the default value for it as router-link.

You only need to add is="a" for the link-atom custom component.

<link-atom :to="link.path" is="a">
  {{ link.name }}
</link-atom>
  • Related