【问题标题】:Custom events in Vue.js 2Vue.js 2 中的自定义事件
【发布时间】:2020-05-15 19:20:40
【问题描述】:

我正试图弄清楚如何让子组件与父组件通信,而不需要在它们之间进行硬绑定。

根据我的阅读,应该是自定义事件。但我无法让父组件接收事件并对其采取行动。

在下面的示例中,我希望单击<child> 中的“执行操作”按钮来触发<parent> 中的doStuff()。我看到指示按钮被单击的日志消息,但我没有看到指示发出的消息已被父级接收到的日志消息。

示例 HTML:

<!DOCTYPE html>
<html>
  <head>
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
  </head>

  <body>
    <div id="app">
      <parent>
        <child></child>
      </parent>
    </div>
  </body>
</html>

示例 Javascript:

Vue.component('parent', {
    props: [],
    template: `
        <div v-on:stuff="doStuff">
            <h1>Hello World (from parent)!</h1>
            <slot></slot>
        </div>
    `,
    methods: {
      doStuff: function() {
        console.log('Do stuff');
      }
    }
});

Vue.component('child', {
    props: [],
    template: `
        <div>
            Hello World (from child)!<br>
            <button v-on:click="performClick">Do stuff</button>
        </div>
    `,
    methods: {
      performClick: function() {
        console.log('Do something');
        this.$emit('stuff');
      }
    }
});

var app = new Vue({
  el: '#app',
})

【问题讨论】:

  • 问题是你在 div 上发出的,而不是任何组件。

标签: vuejs2 vue-component


【解决方案1】:

您对发出的访问是错误的。 stuff 是从子组件发出的,因此您需要在子组件标记 中访问该发出,因此您应该在父组件模板中使用子组件标记。如下所示

Vue.component('parent', {
    props: [],
    template: `
        <div>
            <h1>Hello World (from parent)!</h1>
            <slot :test="doStuff"></slot>
        </div>
    `,
    methods: {
      doStuff: function() {
        console.log('Do stuff');
      }
    }
});

Vue.component('child', {
    props: [],
    template: `
        <div>
            Hello World (from child)!<br>
            <button v-on:click="performClick">Do stuff</button>
        </div>
    `,
    methods: {
      performClick: function() {
        console.log('Do something');
        this.$emit('stuff');
      }
    }
});

var app = new Vue({
  el: '#app'
})
<!DOCTYPE html>
<html>
  <head>
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
  </head>

  <body>
    <div id="app">
      <parent>
        <template slot-scope="scope"><child v-on:stuff="scope.test"></child></template>
      </parent>
    </div>
  </body>
</html>

更新

您需要在父组件中使用slot并设置slot-scope,设置为:{scopeName},然后您可以通过slot-scope从模板访问。当子组件被发射时,你只需要调用那个 {scopeName}

【讨论】:

  • 感谢您的澄清。问题是,在我的预期情况下,&lt;parent&gt; 组件可以是任何类型内容的包装器,因此我不能“硬编码”子组件。最终结果将是父组件是一个内容可变的弹出气泡。子组件可以是文本、表单、选项菜单等。我希望子组件能够在子组件执行某些操作后向其发送close 消息。
猜你喜欢
  • 2019-03-21
  • 2018-12-25
  • 2017-07-15
  • 2020-02-02
  • 1970-01-01
  • 1970-01-01
  • 2023-03-21
  • 1970-01-01
  • 2021-04-22
相关资源
最近更新 更多