如何从这个。$ emit()在vuejs中接收第二个参数?

时间:2018-02-15 12:22:26

标签: javascript vue.js

我在my-input中有自定义输入元素MyInput.vue

<input :value="value" @input="inputOccurred($event.target.value)">

在我的inputOccurred方法中,我发出oninputoccurred自定义事件并传递值:

inputOccurred: function(value){
     this.$emit('oninputoccurred', value);
}

但是如何从父组件接收传递的值?第二个参数(值)从this.$emit()到哪里?

 <my-input @oninputoccurred="printValue(<!-- How do I get the value here -->)"></my-input>

1 个答案:

答案 0 :(得分:1)

以下是向组件:in发送值然后在内部设置组件模型this.value的基本示例,然后在@input通过发送它将当前值发送回父组件

&#13;
&#13;
Vue.component('myInput', {
  template: '#input-template',
  props: ['in'],
  data () {
    return {
      value: this.in
    }
  },
  methods: {
    inputOccurred (e) {
      // set the model
      this.value = e.target.value
      this.$emit('on-out', this.value.split("").reverse().join(""))
    }
  }
});

//
var vm = new Vue({
  el: '#app',
  data () {
    return {
      value: 'Sent from parent, reverse by typing a value'
    }
  },
  methods: {
    setValue (value) {
      this.value = value
    }
  }
});
&#13;
<script src="https://cdn.jsdelivr.net/vue/1.0.16/vue.js"></script>
<div id="app">
  <my-input :in="value" @on-out="setValue"></my-input>
  
  {{ value }}
</div>

<template id="input-template">
  <input :value="value" @input="inputOccurred">
</template>
&#13;
&#13;
&#13;