2017-02-15 78 views
4

我知道如何從Vue實例中刪除列表項。但是,當列表項傳遞給Vue組件時,如何在保持組件與列表數據同步的同時刪除列表項?如何在清單項刪除時刷新Vue組件?

這是用例。考慮一個帶有Markdown編輯器的在線論壇。我們有一個Vue實例,其數據是從服務器獲取的保存評論列表。這些評論應該是用Markdown編寫的。

爲了便於編輯和預覽,我們還有一個組件列表。每個組件都包含一個可編輯的輸入緩衝區以及一個預覽部分。 Vue實例中保存的註釋內容用於初始化輸入緩衝區,並在用戶取消編輯時重置輸入緩衝區。預覽是輸入緩衝區內容的轉換。

下面是一個測試實施:

<template id="comment"> 
    <div> 
     Component: 
     <textarea v-model="input_buffer" v-if="editing"></textarea> 
     {{ preview }} 
     <button type="button" v-on:click="edit" v-if="!editing">edit</button> 
     <button type="button" v-on:click="remove" v-if="!editing">remove</button> 
     <button type="button" v-on:click="cancel" v-if="editing">cancel</button> 
    </div> 
</template> 

<div id="app"> 
    <ol> 
     <li v-for="(comment, index) in comments"> 
      <div>Instance: {{comment}}</div> 
      <comment 
       v-bind:comment="comment" 
       v-bind:index="index" 
       v-on:remove="remove"> 
      </comment> 
     </li> 
    </ol> 
</div> 

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.8/vue.js"></script> 

<script> 
let comments = ['111', '222', '333'] 

Vue.component('comment', { 
    template: '#comment', 
    props: ['comment', 'index'], 
    data: function() { 
    return { 
     input_buffer: '', 
     editing: false, 
    } 
    }, 
    mounted: function() { this.cancel() }, 
    computed: { 
    preview: function() { 
     // This is supposed to be a transformation of the input buffer, 
     // but for now, let's simply output the input buffer 
     return this.input_buffer 
    }, 
    }, 
    methods: { 
    edit: function() { this.editing = true }, 
    remove: function() { this.$emit('remove', this.index) }, 
    cancel: function() { this.input_buffer = this.comment; this.editing = false }, 
    //save: function() {}, // submit to server; not implemented yet 
    }, 
}) 

let app = new Vue({ 
    el: '#app', 
    data: { comments: comments }, 
    methods: { 
    remove: function(index) { this.comments.splice(index, 1); app.$forceUpdate() }, 
    }, 
}) 
</script> 

的問題是,如果我們刪除註釋,該組件沒有相應地刷新。例如,我們在上面的實現中有3條評論。如果您刪除了評論2,則第3項的預覽仍將顯示第2項的內容。僅在按edit後跟cancel纔會更新。我試過app.$forceUpdate(),但是沒有幫助。

回答

2

你只需要在V-for循環添加key屬性類似如下:

<li v-for="(comment, index) in comments" :key="comment"> 

見工作小提琴:https://fiddle.jshell.net/mimani/zLrLvqke/

Vue公司試圖優化渲染,通過提供關鍵屬性,它把那些作爲完全不同的元素,並重新渲染那些正確的。

有關更多信息,請參閱the key documentation

+0

非常感謝。它完美的作品。你知道在文檔的哪個位置我可以查看':key'的用法嗎? – user740006