strategicsdemexico's avatar

Redirect from method in Vue.js with Vue-router

Using vue.router, I have a component to create a post, how can I redirect from the method savePost of my component to other URL using the router?

savePost: function(){
            this.$http.post('/posts', this.post)
            .success(function(post){
                location.href = '/';
                /// Something like.... router.redirect('/')
            });
        },
0 likes
11 replies
veve286's avatar
veve286
Best Answer
Level 8

try this inside your component ?


   this.$route.router.go('/');

5 likes
Ltloafer's avatar

I'm using Vueify and cannot get the router to work in my components. I've brought in Vue-router with npm. Registering it with var VueRouter = require('vue-router'); var router = new VueRouter(); I wanted to use it within a vue-resource method as above and I keep getting router not defined. What am I doing wrong? Thanks

LT

rw3iss's avatar

You need to register the router with Vue after instantiation:

Vue.use(VueRouter)

cdubant's avatar

For ones like me who want to address this on routing based on the URL, see also https://router.vuejs.org/en/essentials/redirect-and-alias.html as you can say maybe if the user goes to /home on Spark for example, you want to redirect him to /dashboard (this was my personal case).

Would translate to something like :

const router = new VueRouter({
    mode: 'history',
    base: __dirname,
    routes: [
        {   
            path: '/dashboard',
            name: 'dashboard',
            component: Dashboard
        },
        {
            path: '/home',
            redirect: '/dashboard'
        }
    ]
})

Please or to participate in this conversation.