Creating Component Dynamically always removes last instance

前端 未结 1 639
忘了有多久
忘了有多久 2021-01-22 13:45

I have a child component and parent component. Parent component renders child component dynamically i.e. on demand and keeps the record in array. When

相关标签:
1条回答
  • 2021-01-22 14:26

    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>

    0 讨论(0)
提交回复
热议问题