简体   繁体   English

Vue.js 组件父事件

[英]Vue.js component parent event

im wondering why my code isn't working.我想知道为什么我的代码不起作用。 I have an event 'leave' which should be called on blur.我有一个事件“离开”,应该在模糊时调用。 The components are displayed properly but when i leave the inputs the event wont be triggered.组件显示正确,但是当我离开输入时,不会触发事件。

 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>

Thanks for your help :)谢谢你的帮助 :)

Your <text-input> component needs to forward (re- emit ) the blur event from the inner <input> element:您的<text-input>组件需要从内部<input>元素转发(重新发出blur事件:

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

Then, <text-input> 's parent could receive it:然后, <text-input>的父母可以收到它:

// 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM