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?
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'] }, ], }, ]
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 me –
Concessive 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 /bar/:subPath*
–
Lungki 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')
this.$router.push({name: 'router-name'})
–
Dewaynedewberry 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.
<a href='...' target="_blank"> ...
–
Schramm href
) but that's all. –
Costrel When inside a component script tag you can use the router and do something like this
this.$router.push('/url-path')
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'
}
});
param
didn't work, though params
works for me. –
Mcghee return router.push({ name: 'publisher-slots' });
On my form submission success area. –
Irresolute Just a dead simple routing:
this.$router.push('Home')
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"),
},
]
window.location = url;
'url' is the web url you want to redirect.
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..
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
.
/path-to-route/${IdVariable}
" . –
Linet 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
I'm using Vue3 and this works for me
router.push({ name: 'myRoute' })
this.$router.push('/path')
if you are using composition API –
Jayson 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.
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
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.
this.$router.push('about')
referencing the the name automatically. –
Angelangela <div id="app">
<a :href="path" />Link</a>
</div>
<script>
new Vue({
el: '#app',
data: {
path: 'https://www.google.com/'
}
});
</script> enter code here
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)
});
);
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>
In case of Laravel + Inertia:
this.$inertia.get(route('route.name', this.modelId));
© 2022 - 2024 — McMap. All rights reserved.