代码之家  ›  专栏  ›  技术社区  ›  yhc44

Vue。js组件父事件

  •  0
  • yhc44  · 技术社区  · 6 年前

    我想知道为什么我的代码不起作用。我有一个活动“离开”,应该在blur上进行。组件显示正确,但当我离开输入时,事件不会被触发。

    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>

    谢谢你的帮助:)

    1 回复  |  直到 6 年前
        1
  •  2
  •   tony19 steve    6 年前

    你的 <text-input> 组件需要转发(re)- emit )那个 blur 来自内心的事件 <input> 要素:

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

    然后 <文本输入> 孩子的父母可以收到:

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