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?
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.
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
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'] }, ], }, ]