使用$ emit

时间:2016-12-16 14:07:49

标签: javascript vue.js vue-component vue-router

我有一个包含组件登录的父视图,当用户登录时,我通过$emit向父母发送回电话

vm.$emit('stateChanged');

我在请求成功时使用它

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)
      }
});

在父视图中我使用

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

并在Vue的方法中定义函数来处理回调,但它从不调用甚至触发错误,但它只有在我使用vm.$parent.$emit('stateChanged');而不是回调$.emit方式时才有效。

其他问题,如果我使用组件作为路由,使用VueRouter,它会给我错误:

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

我正在关注文档Using v-on with Custom Events

家长

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

组件

var data = { email: 'pYKzARYlwW@gmail.com',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 个答案:

没有答案