How to redirect to page and external url in vuejs


Page navigation is one of the basic feature of any website from one page to other page.

In normal pages, Anchor links are used to navigate from one link to another link

<a href="cloudhadoop.com/about">About</a>

The same can be replaced with binding in vuejs

<a :href="cloudhadoop.com/about">
 or 
<a v-bind:href="cloudhadoop.com/about">

This is fixed way of adding the path at html templae that will redirect at server level.

Then how do you navigate to page programmatically? this post talks about navigation of pages programmatically with below approaches

One way is, Vue-router library provides navigation mechanism, and configured to forward into another pages. Another way is to use window.location.href to redirect page.

This blog post talks about below items

  • Forward to other pages in same website
  • Redirect to URL

this post talks about navigation from website.com/about and want to navigate towebsite.com/contact page.

Redirect to page and url in vuejs

There are multiple ways to redirect to other pages.

with inbulit window object

You have to set url programmatically using window.location.href

window.location.href = '/contact';

Redirect to external url, you have to replace path with url in setting path

window.location.href = 'facebook.com/pages/mypage';

with Vue-router Application is configured router in for contact path

const router = new VueRouter({
  routes: [
    {
      path: '/contact',
      name: 'contact',
      component: ContactComponent,
    }
  ]
});

It is very easy with vue-router with push method of router reference with path as well as name of a route.

Forward an page with path as follows

this.$router.push("/contact")

/contact is path of the route that you configured in vue-router declaration

with rounte name, you have to replace path with name as follows

this.$router.push("contact")

External url can be redirected with push as follows

Forward internal page with push is

this.$router.push("facebook.com/pages/mypage")
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.