Vue-router: How to use vue-router inside component to perform redirects?

Created on 6 Sep 2015  ·  7Comments  ·  Source: vuejs/vue-router

Hi

Using vue-router how to perform manual redirect on certain ajax calls ?. Following is sample code.

<template>
  <div class="login-bg">
    <div class="container">
      <form class="form-signup" method="POST" v-on="submit: onSubmitForm">
        <h1 class="text-center">picstats</h1>
        <h2 class="form-signin-heading">Register</h2>
          <div class="alert alert-danger" v-if="error.email">
            {{ error.email }}
          </div>
          <div class="alert alert-danger" v-if="error.password">
            {{ error.password }}
          </div>
         <label for="inputName" class="sr-only">Name</label>
         <input type="text" id="inputName" v-model="user.name" class="form-control" placeholder="Name" required autofocus>
        <label for="inputEmail" class="sr-only">Email address</label>
        <input type="email" id="inputEmail" v-model="user.email" class="form-control" placeholder="Email address" required autofocus>
        <label for="inputPassword" class="sr-only">Password</label>
        <input type="password" id="inputPassword" v-model="user.password" class="form-control" placeholder="Password" required>
        <button class="btn btn-lg btn-primary btn-block" type="submit">Register</button>
        <br/>
        <br/>
        <p class="text-center">Already have account ? <a href="/#/"> Sign in</a></p>
      </form>
    </div>
  </div>
</template>
<script>
module.exports = {
  data:function(){
    return {
      user : {name: '',email: '',password: ''},
      error : ''
    }
  },
  methods: {
        onSubmitForm: function(e)
        {
            e.preventDefault();
            this.$http.post('/api/users',this.user,function(data){
                 router.go('/');
            })
            .error(function(data){
              if(data.errors != 'undefined')
              {
                this.$set('error',data.errors);
              }
            });
        }
    }
}
</script>

Router won't work as it is giving error as undefined. So how do we implement it?

Most helpful comment

in vue-router 2.0 this.$router.push('path-to-go')

All 7 comments

this.$route.router.go() ?

@azamat-sharapov kool thanks

in vue-router 2.0 this.$router.push('path-to-go')

this.$router not work for me

TypeError: Cannot read property '$router' of undefined
at eval (Internal.vue?8b12:94)
at

@elviskudo : you seem to be using () => { ... which locks this into the current context, try function () { ... instead

The previous answers don't work to me.

Try this :
this.$f7.mainView.router.load({url:'/path-to-go'})

Here is good link related to this which helps me.
Just import router and use imported router instead of 'this.route' and use router.push('url') :)
https://laracasts.com/discuss/channels/vue/redirect-from-method-in-vuejs-with-vue-router

Was this page helpful?
0 / 5 - 0 ratings