Creating Component Dynamically always removes last instance

孤者浪人 提交于 2019-12-01 22:58:43

I think your deleting is working in the first fiddle but you're not seeing it correctly because your list is getting shorter if you're deleting one item. So it seems that always the last item is removed.

Also adding an id to your object helps Vue to render the v-for and you can add the key binding to id.

Please have a look at the demo below or this fiddle.

In your application code that you posted in your question:

Is your remove handler called? You're emitting on bus but your listener is attached to this. Please have a look at this fiddle so you're seeing the difference.

Vue.component('child', {
		props:['index', 'data'],
    template: `
        <div>
            data# {{data}}
            <button @click="$emit('delete-me')">Delete</button>
        </div>`
})

Vue.component('parent', {
    template: `
        <div>
            Keep Adding new Instances 
            <button @click="newChild">New</button>
            <hr />
            <child v-for="(row, index) in children" :data="row" 
            v-on:delete-me="deleteThisRow(index)" :key="row.id"
            :index="index"
            ></child>
        </div>`,
        data() {
        	return {
            id: 0,
          	children:[]
          }
    },
    methods: {
    	newChild() {
      	this.children.push({
        	id: this.id++,
        	value: 'new child'
        })
      },
      deleteThisRow(index) {
      			// console.log('index', index, this.children)
            this.children.splice(index, 1);
        }
    }
})

new Vue({
    el: '#app',
    template: `
        <div>
        		<parent />
            
        </div>
    `,
    
    methods: {
        
    }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.3/vue.js"></script>
<div id="app"></div>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!