Call from component to parent with $emit

437 views Asked by At

I have a parent view with component Sign-in , when user has logged in , i send call back to parent with $emit

vm.$emit('stateChanged');

I use it when request success

var vm = this;
$.ajax({
      url: URL+'/auth/login',
      type: 'post',
      data:{'email':data.email,'password':data.password},
      async: false,
      success: function(data) {
                  vm.$emit('stateChanged');
                  console.log();
      },
      error: function(data){
                  console.log(data.responseText)
      }
});

In parent view i use

<sign-in v-on:stateChanged="getLoginState"></sign-in>

and define function in methods of Vue to handle callback , but it never call or even fire error , but it only work if i use vm.$parent.$emit('stateChanged'); instead of callback $.emit way .

Other issue , if i use component as route , using VueRouter , it give me error :

vue.min.js:7 ReferenceError: getLoginState is not defined

I am following docs Using v-on with Custom Events

Parent

const app = new Vue({
         el:'#app',
         data:{
           isLogin:'false',
         },
         methods:{
           getLoginState: function () {
             this.isLogin= true
           }
         }
}

Component

var data = { email: '[email protected]',password: 'secret'}
Vue.component('sign-in', {
    data:function () {
       return data;
     },
    template: '<form action="index.html" class="col-md-12" method="post">\
             <div class="form-group">\
               <label for="email"></label>\
               <input type="email" class="form-control"  id="email" v-model="email" placeholder="E-mail">\
               <p class="help-block">Enter your mail</p>\
             </div>\
             <div class="form-group">\
               <label for="password"></label>\
               <input type="text" class="form-control"   id="password" v-model="password" placeholder="Password">\
               <p class="help-block">Enter your password.</p>\
             </div>\
               <input type="button" v-on:click="doLogin" class="btn btn-default" value="Log in" name="login"/>\
           </form>',
    methods: {
      doLogin: function (event) {
        var vm = this
        $.ajax({
                url: URL+'/auth/login',
                type: 'post',
                data:{'email':data.email,'password':data.password},
                async: false,
                success: function(data) {
                  vm.$parent.$emit('stateChanged');
                },
                error: function(data){
                  console.log(data.responseText)
                }
         });
      }
    }
})
0

There are 0 answers