为什么$ emit在我的Vue组件中不起作用

dge*_*are 3 vuejs2

几个小时以来,我一直在努力解决这个问题。我看不到问题,据我所知,我在这里关注文档:https : //vuejs.org/v2/guide/components-custom-events.html

下面的代码

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="wrap">
  <test-listen>
    <test-emit></test-emit>
  </test-listen>
</div>
<script>
Vue.component('test-listen', {
  data: function(){
    return {};
  },
  methods: {
    customHandler : function(e){
      console.log(e);
      console.log("works");
    }
  },
  template: `
    <div class='test_listen' v-on:custom="customHandler">
      <slot></slot>
    </div>
  `
});

Vue.component('test-emit',{
  data: function(){
    return {};
  },
  methods: {
    clickHandler : function(){
      this.$emit('custom');
    }
  },
  template : `
    <div class='test_emit' v-on:click="clickHandler">
      test
    </div>
  `
});

new Vue({
  el:"#wrap"
});
</script>
<style>
.test_listen{
  display:block;
  padding:20px;
  border:1px solid #000;
}
.test_emit{
  display:block;
  width:100px;
  height:100px;
  background-color:#f0f;
  color:#fff;
  font-weight:700;
  font-size:20px;
}
</style>
Run Code Online (Sandbox Code Playgroud)

但是侦听器绝对绑定到该元素,因为如果我调度vanillaJS CustomEvent,它将触发控制台日志。我想念什么?

Maj*_*azi 5

我在这里只看到一个错误。您应该在子组件上添加v-on。当您从内部$ emit('custom')调用时,它会在父组件上调用“ customHandler”。

工作jsfiddle

    <test-listen>
        <test-emit v-on:custom="customHandler"></test-emit>
    </test-listen>
Run Code Online (Sandbox Code Playgroud)


Har*_*iya 3

这里有两件事是错误的。

  1. 我猜 Vue 事件只能绑定到组件(这里讨论 vue 事件)
  2. 老虎机不适合事件。(来源- Evan You,Vue 作者)

如果你真的想不受限制地到处传递数据,最好使用Global Event Bus Approach

您的代码的工作示例,经过一些细微的修正。

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="wrap">
  <test-listen>
  </test-listen>
</div>
<script>
Vue.component('test-listen', {
  data: function(){
    return {};
  },
  methods: {
    customHandler : function(e){
      console.log(e);
      console.log("works");
    }
  },
  template: `
    <div class='test_listen' >
      <test-emit v-on:custom="customHandler"></test-emit>
    </div>
  `
});

Vue.component('test-emit',{
  data: function(){
    return {};
  },
  methods: {
    clickHandler : function(e){
      // e => event : didnt pass here as console will stuck so
      this.$emit('custom', 'somedata');
    }
  },
  template : `
    <div class='test_emit' v-on:click="clickHandler">
      test
    </div>
  `
});

new Vue({
  el:"#wrap"
});
</script>
<style>
.test_listen{
  display:block;
  padding:20px;
  border:1px solid #000;
}
.test_emit{
  display:block;
  width:100px;
  height:100px;
  background-color:#f0f;
  color:#fff;
  font-weight:700;
  font-size:20px;
}
</style>
Run Code Online (Sandbox Code Playgroud)