Vue js 2:this。$ emit dont Trigger

时间:2016-10-16 08:24:40

标签: javascript vue.js vuejs2

我有一个简单的代码来测试子组件和父组件之间的通信,请参阅vuejs doc:http://vuejs.org/guide/components.html#Using-v-on-with-Custom-Events中的示例。但显然它不适用于父组件

我的jsfiddle:Jsfiddle

HTML:



Vue.component('tasks-item', {
       template: '<div>{{item.title}} <button v-on:click="deleteItem(item)">x</button></div>',
       props: ['item'],
       methods: {
       	deleteItem: function(item){
         	console.log('child click')
            document.getElementById('output').innerHTML='child click : '+item.title
            this.$emit('deleteItem')
         }
       }
})


Vue.component('tasks-list', {
       template: '#tasks-list',
       props: ['tasks'],
       methods: {
       	deleteTask: function(){
         	document.getElementById('output').innerHTML='parent click'
         }
       }
})


new Vue({
	el: '#app',
  data: function(){
  	return {
    	data:[{"id":51,"title":"rr4434","content":"rtrtrrtrtr"},{"id":50,"title":"rrrr","content":"rrr"},{"id":49,"title":"rrrr","content":"rrr"},{"id":48,"title":"rrr","content":"rrr"},{"id":47,"title":"rrr","content":"rrr"},
{"id":46,"title":"c\u00f4 d\u00e2\u0300n","content":"pha\u0309i khong em"},
{"id":45,"title":"we are you","content":"content"},
{"id":44,"title":"cai min nek","content":"co gi kh\u00f4ng"},{"id":43,"title":"abc","content":"dghjj"},{"id":42,"title":"dddd","content":"ddd"},{"id":38,"title":"444","content":"4444"},{"id":36,"title":"rrr","content":"rr"},{"id":35,"title":"rr","content":"rr"},{"id":34,"title":"rrrr","content":"rrr"},{"id":33,"title":"rrr","content":"rr"}]
    }
  },
  methods: {
  }
})
&#13;
<script src="https://unpkg.com/vue@next/dist/vue.js"></script>
<div id="app">
   <div id="output">click output</div>
   <hr/>
    <tasks-list :tasks="data"></tasks-list>
</div>
<template id="tasks-list">
     <div>
        <div v-for="item in tasks">
           <tasks-item :item="item" v-on:deleteItem="deleteTask()"></tasks-item>
        </div>
     </div>
</template>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

更改     this.$emit('deleteItem') 至     this.$emit('delete-item')

以及模板修订组件内部的v-on     v-on:deleteItem 至     v-on:delete-item

您可以在https://vuejs.org/v2/guide/components-custom-events.html

阅读更多内容