236

I'd like to make a redirection in Vue.js similar to the vanilla javascript

window.location.href = 'some_url'

How could I achieve this in Vue.js?

Saurabh
  • 71,488
  • 40
  • 181
  • 244
Jimmy Obonyo Abor
  • 7,335
  • 10
  • 43
  • 71
  • 1
    Do you mean a redirect to a route defined in vue router '/my/vuerouter/url'? Or do you a browser redirect to http://some-url.com? – hitautodestruct Jan 30 '19 at 05:16

18 Answers18

327

If you're using Vue Router, you can use router.push(path) to navigate to any particular route programmatically (note that this was router.go(path) prior to Vue 2).

The router itself can be accessed from the $router property on the Vue instance, which means that you can access push from within a component with this.$router.push(path).

You can also use object syntax for more control, including navigating to preconfigured named routes. From the documentation:

// object
router.push({ path: 'home' })

// named route
router.push({ name: 'user', params: { userId: '123' } })

// with query, resulting in /register?plan=private
router.push({ path: 'register', query: { plan: 'private' } })

// with hash, resulting in /about#team
router.push({ path: '/about', hash: '#team' })

Vue router aside, window.location.href = 'some url'; works fine for non single-page apps.


If you're looking for more permanent redirection, rather than just programmatic navigation, e.g. redirecting all example.com/foo hits to example.com/bar, then you should use Vue Router's redirect or alias features.

Redirect

Redirects go in the route configuration, and let you tell Vue Router to always redirect a given path to somewhere else, e.g. navigating to /foo will bounce you to /bar instead:

const routes = [{ path: '/foo', redirect: '/bar' }];

These paths can also be dynamic, e.g.:

const routes = [{ path: '/foo/:subPath*', redirect: '/bar/:subPath*' }];
// example.com/foo/profile?id=123 --> example.com/bar/profile?id=123

Alias

Aliases are like redirects, routing traffic from one location to another, but they don't change the user's URL. This gives greater flexibility by allowing you to map arbitrary parts of a UI structure to any path you desire.

From the documentation:

const routes = [
  {
    path: '/users',
    component: UsersLayout,
    children: [
      // this will render the UserList component for these 3 URLs:
      // - /users
      // - /users/list
      // - /people
      { path: '', component: UserList, alias: ['/people', 'list'] },
    ],
  },
]
zcoop98
  • 2,590
  • 1
  • 18
  • 31
Jeff
  • 24,623
  • 4
  • 69
  • 78
  • 4
    In my case the use is to direct to another non single-page – Jimmy Obonyo Abor Feb 27 '16 at 17:19
  • 13
    I was getting : `Uncaught ReferenceError: router is not defined` error, How to inject router in component? – Saurabh Oct 28 '16 at 06:45
  • 12
    `this.$router.push('routename)` – ka_lin Jun 24 '19 at 07:24
  • ```this.$router.push({ name: 'routename' })``` works for me – Osh Mansor Dec 20 '19 at 02:55
  • So, where to put this `window.location.href` then? If we put it in mounted(), it will take a lot of time and the "original" page will flash by before redirecting. What at least I am looking for is an instant redirect with no delays, preferrably on the router directly. – Marcus Jul 08 '20 at 09:58
  • 2
    @ka_lin you made a typo, I'm assuming you meant this.$router.push('routename') – James Dube Aug 19 '20 at 11:38
  • I don't think the dynamic redirect works anymore, using the code above with vue router 4 you simply get redirected to the literal path `/bar/:subPath*` – jdnz May 12 '23 at 10:49
114

According to the docs, router.push seems like the preferred method:

To navigate to a different URL, use router.push. This method pushes a new entry into the history stack, so when the user clicks the browser back button they will be taken to the previous URL.

source: https://router.vuejs.org/en/essentials/navigation.html

FYI : Webpack & component setup, single page app (where you import the router through Main.js), I had to call the router functions by saying:

this.$router

Example: if you wanted to redirect to a route called "Home" after a condition is met:

this.$router.push('Home') 
Dave Sottimano
  • 1,324
  • 2
  • 10
  • 15
59

just use:

window.location.href = "http://siwei.me"

Don't use vue-router, otherwise you will be redirected to "http://yoursite.com/#!/http://siwei.me"

my environment: node 6.2.1, vue 1.0.21, Ubuntu.

Siwei
  • 19,858
  • 7
  • 75
  • 95
  • 1
    I don't see any reason, why this should be in double quotes..? – Moritz Jun 29 '16 at 06:30
  • 1
    Actually [standardjs](http://standardjs.com/) says "Use single quotes for strings except to avoid escaping." – Moritz Jun 29 '16 at 06:31
  • this was some time ago but i actually i solved this by using single quotes , but i guess double quotes should also work and might usefull in complex links . – Jimmy Obonyo Abor Jun 29 '16 at 07:01
  • check the vue version first. in the early version, maybe vue doesn't care the code convention. However in my environment, code convention will cause compile error ( from es6 compiled to vanilla js ) . If you haven't use the 'ES6' node module, maybe it will be ok. – Siwei Jun 30 '16 at 03:22
  • what if you would like to open it on a new tab? – Fthi.a.Abadi Jan 28 '20 at 08:09
  • @Fthi.a.Abadi just forget vue.js, treat the page as traditional web page, use ` ...` – Siwei Jan 30 '20 at 07:55
  • SPAs should not be nuked by such navigation, bad advice. It may be okay for a new tab or an anchor navigation (if using `href`) but that's all. – kissu Nov 14 '22 at 10:47
40

When inside a component script tag you can use the router and do something like this

this.$router.push('/url-path')
kissu
  • 40,416
  • 14
  • 65
  • 133
Njeru Cyrus
  • 1,753
  • 21
  • 22
33

if you want to route to another page use this

this.$router.push({path: '/pagename'});

if you want to route to another page with params use this

this.$router.push({
  path: '/pagename', 
  params: {
    param1: 'value1', 
    param2: 'value2'
  }
});
kissu
  • 40,416
  • 14
  • 65
  • 133
Bagzie
  • 482
  • 5
  • 7
  • 1
    Thank you my hero, you saved the day! By the way, `param` didn't work, though `params` works for me. – Miron Dec 21 '20 at 08:12
  • I do on vuexy theme with `return router.push({ name: 'publisher-slots' });` On my form submission success area. – lincolndu Aug 12 '22 at 05:51
15

Just a dead simple routing:

this.$router.push('Home')
kissu
  • 40,416
  • 14
  • 65
  • 133
13

can try this too ...

router.push({ name: 'myRoute' })
kissu
  • 40,416
  • 14
  • 65
  • 133
12

If anyone wants permanent redirection from one page /a to another page /b


We can use redirect: option added in the router.js. For example if we want to redirect the users always to a separate page when he types the root or base url /:

const router = new Router({
  mode: "history",
  base: process.env.BASE_URL,
  routes: [
    {
      path: "/",
      redirect: "/someOtherPage",
      name: "home",
      component: Home,
      // () =>
      // import(/* webpackChunkName: "home" */ "./views/pageView/home.vue"),

    },
   ]
Rakibul Haq
  • 1,348
  • 23
  • 32
8
window.location = url;

'url' is the web url you want to redirect.

Rayees Pk
  • 2,503
  • 1
  • 23
  • 19
8

So, what I was looking for was only where to put the window.location.href and the conclusion I came to was that the best and fastest way to redirect is in routes (that way, we do not wait for anything to load before we redirect).

Like this:

routes: [
    {
        path: "/",
        name: "ExampleRoot",
        component: exampleComponent,
        meta: {
            title: "_exampleTitle"
        },
        beforeEnter: () => {
            window.location.href = 'https://www.myurl.io';
        }
    }]

Maybe it will help someone..

Marcus
  • 8,230
  • 11
  • 61
  • 88
5

You can also use the v-bind directly to the template like ...

<a :href="'/path-to-route/' + IdVariable">

the : is the abbreviation of v-bind.

menepet
  • 796
  • 13
  • 17
5

this.$router.push can be used to redirect pages in vue.js

this.$router.push(url);

Example this.$router.push('home'); this method will not refresh the pages

vishwas
  • 94
  • 1
  • 3
5

I'm using Vue3 and this works for me

router.push({ name: 'myRoute' })
Cyebukayire
  • 795
  • 7
  • 14
1

To stay in line with your original request:

window.location.href = 'some_url'

You can do something like this:

<div @click="this.window.location='some_url'">
</div>

Note that this does not take advantage of using Vue's router, but if you want to "make a redirection in Vue.js similar to the vanilla javascript", this would work.

Brad Ahrens
  • 4,864
  • 5
  • 36
  • 47
1

If you're using the Composition API, the approach is to use something like this

<script setup>
import { useRouter } from 'vue-router'
const router = useRouter()

router.push({ name: 'about' })
</script>

You can check the name of your routes by using the Vue devtools

enter image description here

I recommend using name too because you will not need to rewrite all the buttons/links if you want to update some path one day.

kissu
  • 40,416
  • 14
  • 65
  • 133
0
<div id="app">
   <a :href="path" />Link</a>
</div>

<script>
      new Vue({
        el: '#app',
        data: {
          path: 'https://www.google.com/'
        }
      });
</script> enter code here
Yash
  • 19
  • 2
0

Get specific page from api The easiest way is to add another parameter to the URL that will break the cache.

router.replace(data.current + '?t=' + (new Date()).getTime())

For example

router.beforeEach((to, from, next) => {

axios
    .get('http://domazin.com/currentpage')
    .then(response => {
     const data = response.data
       if (to.path != data.current) {
              router.replace(data.current + '?t=' + (new Date()).getTime())
       } else {
          next()
       }
    })
    .catch(error => {
        console.log(error)
});

);
anson
  • 1,436
  • 14
  • 16
0

Vue3.js redirect

Vue3 js global redirect could be define using this method in main.ts

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'

const app = createApp(App)
app.config.globalProperties.$redirect = (page) => {router.push(page)}
app.use(router).mount('#app')

Component

<button @click="$redirect('/login')" type="button" class="btn ">Login</button>
Muhammad Shahzad
  • 9,340
  • 21
  • 86
  • 130