【问题标题】:Vue.js component parent eventVue.js 组件父事件
【发布时间】:2018-10-29 08:48:14
【问题描述】:

我想知道为什么我的代码不起作用。我有一个事件“离开”,应该在模糊时调用。组件显示正确,但是当我离开输入时,不会触发事件。

Vue.component('text-input', {
		props:['args'],
		template: '<input :id="args.id" :type="args.type"/>'
})

App = new Vue({
		el : '#app',
		data: {
			inputs : [
				{ id : 'nickname', type : 'text'},
				{ id : 'email' , type:'email'},	
			]
		},
		methods : {
			leave : function(event) {
				
			var id = $(event.target).attr('id');
		  console.log('left object ' + id);
	  }
  }
})
  
<div id='app'>
  <div class="form-group">
    <text-input 
      class="form-control"
      v-for="input in inputs"
      v-bind:args="input"
      v-bind:key="input.id"
      v-model="input.id"
      v-on:blur="leave"
      />
  </div>
</div>

感谢您的帮助:)

【问题讨论】:

  • v-on:emitemit 事件设置事件处理程序 (leave())。 text-input 组件是否发出 emit 事件?
  • @tony19 对不起,我的意思是模糊而不是发射。我编辑了上面的代码。感谢您的评论

标签: javascript html events vue.js components


【解决方案1】:

您的&lt;text-input&gt; 组件需要从内部&lt;input&gt; 元素转发(重新emitblur 事件:

// text-input
template: `<input @blur="$emit('blur')">`

然后,&lt;text-input&gt; 的父母可以收到它:

// parent of text-input
<text-input @blur="leave" />

Vue.component('text-input', {
		props:['args'],
		template: `<input :id="args.id" :type="args.type" @blur="$emit('blur', $event)"/>`
})

new Vue({
  el: '#app',
  data() {
    return {
      inputs: [
        {id: 1},
        {id: 2},
      ] 
    }
  },
  methods: {
    leave(e) {
      console.log('leave', e.target.id)
    }
  }
})
<script src="https://unpkg.com/vue@2.5.16"></script>

<div id="app">
  <div class="form-group">
    <text-input 
      class="form-control"
      v-for="input in inputs"
      v-bind:args="input"
      v-bind:key="input.id"
      v-model="input.id"
      v-on:blur="leave"
      />
  </div>
</div>

【讨论】:

    猜你喜欢
    • 2020-08-07
    • 2017-11-07
    • 2018-09-01
    • 1970-01-01
    • 2017-04-25
    • 1970-01-01
    • 2019-10-10
    • 2017-10-22
    • 2017-01-04
    相关资源
    最近更新 更多