61

This may be simple, but I've looked over documentation and can't find anything about it. I want to have my 'github' link redirect to say, github.com. However, its just appending 'https://github.com' to my url instead of following the link. Here is a snippet:

 <BreadcrumbItem to='https://github.com'>
    <Icon type="social-github"></Icon>
 </BreadcrumbItem>

(This is using iView for custom CSS, but 'to' works in the same way as router-link).

What ends up happening is this: enter image description here

6
  • 5
    For external links, just use <a href="..."> to point directly to whatever you're linking to. vue-router is only needed for internal links. Commented May 31, 2018 at 21:26
  • That doesn't really work, considering I can't use the <a> tag here, and its being abandoned for 'to'
    – nateph
    Commented May 31, 2018 at 21:29
  • For now, at least, that's how it works. The <a> tag is not being "abandoned"; to is a vue construct that gives the router a chance to rewrite the url to point back to the SPA. One way would be to build that logic into your BreadcrumbItem component, to use <a href="..."> if the attribute has a http(s) protocol or <router-link> otherwise. Commented May 31, 2018 at 21:36
  • Thank you, someone in that thread had a good workaround as well.
    – nateph
    Commented May 31, 2018 at 21:43
  • 1
    Now that I look: Possible duplicate of Vue2 navigate to external url with location.href (One answer there includes another technique I hadn't known about -- "navigation guards" -- that may suit here if you only have a small number of external links to deal with) Commented May 31, 2018 at 21:48

12 Answers 12

56

I read Daniel's Link and found a workaround:

{
     path: '/github',
     beforeEnter() {location.href = 'http://github.com'}
}
3
39
<a :href="'//' + websiteUrl" target="_blank">
  {{ url }}
</a>
0
20

If you use vuetify, you can use v-list-item, v-card or v-btn.

They all have a property target which you can set to _blank e.g.:

<v-list-item href="https://google.com" target="_blank">Google</v-list-item>
16

I'm late to the party, but I think my solution is more simple and elegant:

<component
  :is="item.link.startsWith('http') ? 'a' : 'router-link'"
  v-for="item in navigationLinks"
  :key="item.link"
  :to="item.link"
  :href="item.link"
>
  {{ item.name }}
</component>
1
  • 3
    Although late to the party, this is indeed the solution that keeps things simple and makes relevant use of the Vue.js tools. The dynamic component approach is perfectly fitted here. Thanks ! Commented May 12, 2023 at 7:56
12

You can either:

  • use a normal link <a href=...
  • use a @click handler and change window.location = http:// there.
3
  • I think you cannot use window.location inside a click event handler. I should be window.location.href = "http://...."
    – pinki
    Commented Nov 11, 2018 at 9:05
  • No. I want to be able to right-click the link.
    – Joeri
    Commented Nov 1, 2021 at 10:24
  • No. I want to be able to use :to="var" without having 2 solutions in one component.
    – Joeri
    Commented Nov 1, 2021 at 10:25
5

const github = { template: '<div>github</div>'}

	const routes = [
		{ 
			path: '/github',
			beforeEnter() {location.href = 'http://github.com'},
			component: github
		}
		]

	const router = new VueRouter({
		routes
		})

	const app = new Vue({
		router
		}).$mount('#app')
<head>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
	  <script src="https://unpkg.com/vue/dist/vue.js"></script>
	  <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
    </head>
<body>    
<div id="app">
  <li><router-link to="/github">github.com</router-link></li>
  <router-view></router-view>
</div>
</body>

1
  • 4
    This is overkill for a simple function.
    – Ishmael
    Commented Jul 3, 2019 at 15:45
5

A more dynamic way if you need it is to just override certain methods to detect when a route should be handled in an external manner using route.meta.external:

  // Override matcher to fix external links.
  const match = router.matcher.match
  router.matcher.match = (...args) => {
    let route = match.apply(router, args)
    if (!route.meta.external) {
      return route
    }
    return Object.freeze({...route, fullPath: route.path})
  }

  // Override resolver to fix external links.
  const resolve = router.resolve
  router.resolve = (...args) => {
    const resolved = resolve.apply(router, args)
    if (resolved.route.meta.external) {
      resolved.href = resolved.route.fullPath
    }
    return resolved
  }

  // Handle external routes.
  router.beforeEach((to, from, next) => {
    if (to.meta.external) {
      if (to.meta.newWindow) {
        window.open(to.fullPath)
      }
      else {
        window.location.replace(to.fullPath)
      }
      return next(false)
    }
    next()
  })
2

Just put the link block inside the breadcrumb item like this:

 <BreadcrumbItem>
  <a href="https://github.com">
    <Icon type="social-github"/>
  </a>
 </BreadcrumbItem>
2

Just do "//" instead of http or https. This works for me in router file.

1
  • good solution for those who are using :href Commented Feb 28 at 8:26
1

I would create a new route in my router config file with the route to my external link opening in a a new tab.

{
  name: "Github",
  beforeEnter() {
    window.open('https://www.github.com/', '_blank')
  },
  component: MyComponent,
},

Then in my template I would create a simple button that calls a function to the new route with the external link.

<button @click="onUserClick('Github')">Github</button>
setup () {
  const router = useRouter()
  const onUserClick = (linkTo) => {
    router.push({ name: linkTo })
  }
  return {onUserClick}
}

This will allow you have to multiple links to external routes very easily. IE social media pages without cluttering up your component.

0

I was stuck with the same issue in Vue JS. Here are my codes. Not only does it lead to a new location but also opens a new tab.

<div id="top-socials">
 <ul>
    <li v-for="icon in socialIcons" :key="icon">
        <img @click="socialClicked(icon)" :src="icon" 
     style="width:25px;height:25px;"/>
    </li>

</ul>
</div>
  export default {
data(){
    return{
        socialIcons:[facebook,instagram,tiktok,youtube]
    }
},
  methods:{
  socialClicked(v){
   if(v.includes(tiktok)){
    console.log(v)
   }
   else if(v.includes(youtube)){
    var anchor = document.createElement('a');
    anchor.href = 'https://www.youtube.com/@novathewonderdog9404';
    anchor.target="_blank";
    anchor.click();

    console.log("You Tube was clicked")
   }
   else if(v.includes(instagram)){
    console.log("Instagram was clicked")
   }
   else if(v.includes(facebook)){
    console.log("Facebook was clicked")
   }
  }
}

I guess you could do the same with BreadCrumbs

0

Building up on @Nirgn's answer:

  • Not only text can be linked, thus the use of a slot;
  • Also, if a RouterLink is set to be rendered and href is falsy (e.g null or undefined), then there is no href attribute in the final markup. Although, Vue's soft navigation still works (at least, for Vue Router 4.X & Vue 3.X), but it seems like an issue for SSR when proper link should be placed in the markup right away for SEO.

So, here goes improved version. It results in either a plain <a> or Vue's <RouterLink> around the slot. Both with proper attributes (either href or to):

<template>
  <Component
    v-bind:is="componentName"
    v-bind:[linkAttr]="link"
  >
    <slot />
  </Component>
</template>

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

defineOptions({
  name:         'Link',
  inheritAttrs: false,
});

const props = defineProps({
  to: {
    type:    Object,
    default: () => {},
  },

  href: {
    type:    String,
    default: '',
  },
});

const componentName = computed(() => {
  return props.href ? 'a' : 'RouterLink';
});

const link = computed(() => {
  return props.href || props.to;
});

const linkAttr = computed(() => {
  return props.href ? 'href' : 'to';
});
</script>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.