Vue.js redirection to another page
Asked Answered
H

19

248

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?

Hymenopterous answered 27/2, 2016 at 1:15 Comment(1)
Do you mean a redirect to a route defined in vue router '/my/vuerouter/url'? Or do you a browser redirect to some-url.com?Outport
G
343

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'] },
    ],
  },
]
Guaiacum answered 27/2, 2016 at 8:43 Comment(7)
In my case the use is to direct to another non single-pageHymenopterous
I was getting : Uncaught ReferenceError: router is not defined error, How to inject router in component?Association
this.$router.push('routename)Gerbold
this.$router.push({ name: 'routename' }) works for meConcessive
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.Verniavernice
@Gerbold you made a typo, I'm assuming you meant this.$router.push('routename')Resurrection
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*Lungki
C
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') 
Costa answered 26/2, 2017 at 3:58 Comment(5)
This question has nothing to do with compilation (webpack) .Hymenopterous
Thanks for the downvote, even though most people will be developing with the vue cli, webpack, router and store/vuex and will likely run into the problem of not being able to call the router.Costa
@JimmyObonyoAbor hiyo comment na downvote utasema unamlipa hahaTurnbull
@Turnbull he he he , sawa tushasikia ! i got a react kazi , ping me if you got skills ...Hymenopterous
it is clear to say this.$router.push({name: 'router-name'})Dewaynedewberry
S
62

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.

Schramm answered 29/6, 2016 at 6:24 Comment(7)
I don't see any reason, why this should be in double quotes..?Jsandye
Actually standardjs says "Use single quotes for strings except to avoid escaping."Jsandye
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 .Hymenopterous
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.Schramm
what if you would like to open it on a new tab?Bobette
@Bobette just forget vue.js, treat the page as traditional web page, use <a href='...' target="_blank"> ...Schramm
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.Costrel
A
41

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

this.$router.push('/url-path')
Anderson answered 25/3, 2018 at 17:22 Comment(0)
T
34

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'
  }
});
Tremor answered 29/8, 2019 at 9:38 Comment(2)
Thank you my hero, you saved the day! By the way, param didn't work, though params works for me.Mcghee
I do on vuexy theme with return router.push({ name: 'publisher-slots' }); On my form submission success area.Irresolute
P
16

Just a dead simple routing:

this.$router.push('Home')
Photogrammetry answered 30/12, 2018 at 13:3 Comment(1)
see comment by kissu to my comment regarding direct use of a simple string instead of a json wrapped name.Angelangela
Z
13

can try this too ...

router.push({ name: 'myRoute' })
Zashin answered 17/7, 2018 at 12:8 Comment(0)
B
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"),

    },
   ]
Bifocal answered 10/7, 2019 at 11:13 Comment(0)
A
8
window.location = url;

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

Aarika answered 21/7, 2018 at 12:46 Comment(0)
V
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..

Verniavernice answered 8/7, 2020 at 10:5 Comment(0)
L
6

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.

Linet answered 7/5, 2019 at 13:28 Comment(1)
You can also use the ES6 Syntax: :href="/path-to-route/${IdVariable}" .Linet
B
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

Boris answered 1/4, 2021 at 6:6 Comment(0)
G
5

I'm using Vue3 and this works for me

router.push({ name: 'myRoute' })
Greenlee answered 4/2, 2022 at 5:12 Comment(2)
this is only working answer at moment.Tricycle
or use this.$router.push('/path') if you are using composition APIJayson
P
2

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.

Pr answered 14/7, 2020 at 10:52 Comment(0)
C
2

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.

Costrel answered 20/10, 2022 at 8:46 Comment(2)
You could also combine ist with Mohammad Mahdi KouchakYazdi answer by just using this.$router.push('about') referencing the the name automatically.Angelangela
@DirkSchumacher that pushes the string and not the route name tbh, quite different and not as flexible if you need to update your endpoints one day. While if you use a name, you can still keep your code the same from the inside.Costrel
A
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
Asthmatic answered 9/5, 2019 at 9:55 Comment(0)
D
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)
});

);
Drumhead answered 30/4, 2021 at 8:39 Comment(0)
D
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>
Desert answered 5/7, 2021 at 10:19 Comment(0)
P
0

In case of Laravel + Inertia: this.$inertia.get(route('route.name', this.modelId));

Phillie answered 14/9, 2023 at 13:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.