Vue实例的$ on方法不起作用

时间:2018-05-15 03:11:24

标签: vue.js vuejs2 vuex

我刚刚在main.js文件中创建了一个事件总线,如下所示:

main.js

Vue.prototype.$bus = new Vue()

之后,我只是编写了一些代码来测试事件总线,如下所示:

TestComponent

<template>
  <div>
      <div class="account-modal_form">
          <form action="" @submit.prevent="formSubmit">
                <div class="account-modal_form__group" :class="{ warning: errors.has('password') }">
                    <div class="account-modal_form__input">
                        <input name="password" :type="passwordType" placeholder="" class="width-316" v-validate="'required'" v-model="password">
                        <i class="account-modal_form__viewpass" @click="togglePassword"></i>
                    </div>
                    <span class="account-modal_form__warning" v-show="errors.has('password')">
                        {{ errors.first('password') }}
                    </span>
                </div>
                {{ errors }}
                <div class="account-modal_form__group">
                    <button type="submit" class="btn btn--primary btn--large">next</button>
                    <button type="button" class="btn btn--default" @click="cancelAction">cancel</button>
                </div>
          </form>
      </div>
  </div>
</template>

<script>
import { API } from '@/api'

export default {
    data() {
        return {
            passwordType: 'password',
            password: ''
        }
    },
    methods: {
        created() {
            this.$bus.$on('test', () => console.log('test'));
        },
        nextStep() {
            this.$bus.$emit('test');
        },
        formSubmit() {
            this.nextStep();
        }
    }
}
</script>

当我点击提交按钮时,我想首先提交表单并调用nextstep发出一个事件,但是$ on事件没有输出。

1 个答案:

答案 0 :(得分:3)

您在$emit之前运行$on,因此当您触发事件时,此时没有侦听器,最好在组件created生命周期中注册侦听器event,否则每当你运行测试方法时,你都会注册一个新的监听器:

Vue.prototype.$bus = new Vue();

Vue.component('spy-component', {
  template: '<p>{{this.text}}</p>',
  data() {
    return {
      text: '',
    }
  },
  created() {
    this.$bus.$on('sendOriginPassword', (text) => {
      this.text = text;
    });
  }
})

Vue.component('test-component', {
  template: '<button @click="test">Click me</button>',
  created() {
        this.$bus.$on('sendOriginPassword', () => {
      console.log('I am listening event')
    });
  },
  methods: {
    test() {
      this.$bus.$emit('sendOriginPassword', 'Can you hear me?');
    }
  }
});

new Vue({
  el: "#app",
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>
<div id="app">
  <spy-component></spy-component>
  <test-component></test-component>
</div>