You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue实例$on方法失效求助:事件总线触发无输出

解决Vue事件总线$on无响应的问题

嘿,我看到你的问题了——点击提交按钮后事件总线的test事件没有任何输出,核心问题其实是生命周期钩子的位置写错了,咱们一步步来解决:

1. 最关键的错误:created钩子被嵌套在methods里了

在Vue组件选项中,created是生命周期钩子函数,它应该和data、methods处于同一层级,而不是放在methods对象内部。你现在的写法导致created根本没有被执行,自然也就没注册上事件监听。

2. 修改后的代码示例

我帮你调整了TestComponent的代码,重点修正了created的位置,同时补充了表单验证逻辑(确保表单合法后再触发事件):

<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: ''
    }
  },
  // 把created移到组件选项顶层,和methods同级
  created() {
    console.log('组件已创建,正在注册事件总线监听');
    this.$bus.$on('test', () => console.log('test event triggered!'));
  },
  methods: {
    togglePassword() {
      // 补全密码显示/隐藏的逻辑
      this.passwordType = this.passwordType === 'password' ? 'text' : 'password';
    },
    cancelAction() {
      // 这里可以添加取消按钮的逻辑
      console.log('cancel clicked');
    },
    nextStep() {
      console.log('触发test事件');
      this.$bus.$emit('test');
    },
    formSubmit() {
      // 先执行表单验证,通过后再触发下一步
      this.$validator.validate().then(valid => {
        if (valid) {
          this.nextStep();
        } else {
          console.log('表单验证失败,请检查输入');
        }
      });
    }
  }
}
</script>

3. 额外排查点(如果修改后还是没响应)

  • 确认main.js中的事件总线创建正确:Vue.prototype.$bus = new Vue()要写在创建根Vue实例之前,比如:
    import Vue from 'vue'
    import App from './App.vue'
    
    // 先挂载事件总线到原型
    Vue.prototype.$bus = new Vue()
    
    new Vue({
      render: h => h(App)
    }).$mount('#app')
    
  • 如果是跨组件通信,确保监听事件的组件已经被挂载(比如如果是另一个组件监听test事件,要保证它在触发事件的组件之前创建)。
  • 在nextStep中添加console.log(this.$bus),确认事件总线实例存在,不是undefined。

这样调整后,点击提交按钮,表单验证通过后就会触发test事件,控制台应该能看到对应的输出了。

内容的提问来源于stack exchange,提问作者ChenLee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:52:48