【问题标题】:emit event from slot to grandparen从插槽向祖父母发出事件
【发布时间】:2018-06-06 05:54:02
【问题描述】:

我有以下情况:

var grandParend = new Vue({
  components:[parent,child]
  el: '#app',
  template: 
    <parent>
      <child v-on:my-event="eventHandler"><child>
    <parent>
  data: {
    message: 'Hello Vue!'
  },
   methods:{
     eventHandler(){
            // event handler
     }

})

对于孩子

 Vue.component('child', {
 template: '<button @click="onClick">emit event</button>',
   methods:{ 
     onClick(){
       this.$emit('my-event')
     }

})

如何将事件从子级发送到直接父级? 如何将事件从孩子发送给祖父母?

谢谢

【问题讨论】:

    标签: vuejs2 vue-component


    【解决方案1】:

    您可以简单地使用events 从您的子组件发出事件并在您的(大)父级中处理它们。

    我做了一个小提琴来演示你的例子:https://jsfiddle.net/oLojabhg/2/

    <div id="app">
    </div>
    
    var child = Vue.component('child', {
     template: '<button @click="onClick">emit event from child</button>',
       methods:{ 
         onClick(){
           this.$emit('my-event')
         }
       }
    })
    
    var grandParend = new Vue({
      components: { parent: parent, child: child },
      el: '#app',
      template: '<parent><child v-on:my-event="eventHandler"></child></parent>',
       methods:{
         eventHandler(){
            console.log('event handled!')
         }
       }
    })
    

    请注意,您实际上无法将侦听器添加到插槽,但在大多数用例中,这应该不是问题。更多信息可以在这里找到:

    1. https://github.com/vuejs/vue/issues/4332
    2. https://github.com/vuejs/vue/issues/4781

    【讨论】:

      猜你喜欢
      • 2020-04-15
      • 1970-01-01
      • 2020-04-28
      • 1970-01-01
      • 2021-01-14
      • 1970-01-01
      • 2016-10-24
      • 2020-07-25
      • 2019-05-21
      相关资源
      最近更新 更多