代码之家  ›  专栏  ›  技术社区  ›  Andrew Li

Vue应用程序能否捕获js中孩子发出的事件?

  •  1
  • Andrew Li  · 技术社区  · 8 年前


    正常情况下 Vue 使用 event 向父级发送数据时。
    例如,

    Vue.component('child', {
     template: `
      <div class="myitem">
         <button v-on:click="senddata()">
            Send Data
         </button>
     </div>`,
       methods:{
          senddata:function(){
             this.$emit('data', 'testdata');
          }
       }
     })
    

    <child v-on:data="eventHandler" ref="child"></child>
    

    在父方法中,有一个 eventHandler 以处理从子级发送的数据。
    child 组件发出事件 data 事件处理程序

    methods: {
        eventHandler: function (data) {
           console.log('received data: ' + data);   
        }
    }
    

    这很有效。
    但我想加上 事件处理程序 在密码里。

    this.$refs.child.data().then(function(data){
       //According to the data..., the app want to process data...
    
    });
    

    1 回复  |  直到 8 年前
        1
  •  1
  •   Decade Moon    8 年前

    但我想在代码中添加eventHandler。

    然后你需要使用 Programmatic Event Listeners API $on :

    mounted() {
      this.$refs.child.$on('data', this.eventHandler);
    },
    
    methods: {
      eventHandler(data) {
        ...
      }
    },
    

    在这个特定的例子中,您需要在 mounted created 钩子。

    推荐文章