256

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?

1
  • 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? Commented Jan 30, 2019 at 5:16

19 Answers 19

352

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'] },
    ],
  },
]
Sign up to request clarification or add additional context in comments.

8 Comments

In my case the use is to direct to another non single-page
I was getting : Uncaught ReferenceError: router is not defined error, How to inject router in component?
this.$router.push('routename)
this.$router.push({ name: 'routename' }) works for me
@ka_lin you made a typo, I'm assuming you meant this.$router.push('routename')
|
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') 

5 Comments

This question has nothing to do with compilation (webpack) .
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.
@JimmyObonyoAbor hiyo comment na downvote utasema unamlipa haha
@Cholowao he he he , sawa tushasikia ! i got a react kazi , ping me if you got skills ...
it is clear to say this.$router.push({name: 'router-name'})
65

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.

7 Comments

I don't see any reason, why this should be in double quotes..?
Actually standardjs says "Use single quotes for strings except to avoid escaping."
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 .
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.
what if you would like to open it on a new tab?
|
41

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

this.$router.push('/url-path')

Comments

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'
  }
});

2 Comments

Thank you my hero, you saved the day! By the way, param didn't work, though params works for me.
I do on vuexy theme with return router.push({ name: 'publisher-slots' }); On my form submission success area.
16

Just a dead simple routing:

this.$router.push('Home')

1 Comment

see comment by kissu to my comment regarding direct use of a simple string instead of a json wrapped name.
13

can try this too ...

router.push({ name: 'myRoute' })

Comments

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"),

    },
   ]

Comments

8
window.location = url;

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

Comments

8

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.

1 Comment

You can also use the ES6 Syntax: :href="/path-to-route/${IdVariable}" .
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..

Comments

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

Comments

5

I'm using Vue3 and this works for me

router.push({ name: 'myRoute' })

2 Comments

this is only working answer at moment.
or use this.$router.push('/path') if you are using composition API
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.

Comments

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.

2 Comments

You could also combine ist with Mohammad Mahdi KouchakYazdi answer by just using this.$router.push('about') referencing the the name automatically.
@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.
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

Comments

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)
});

);

Comments

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>

Comments

0

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.