私はVueインスタンスからリスト項目を削除する方法を知っています。ただし、リスト項目がVueコンポーネントに渡されるとき、リスト項目との同期を保ちながらリスト項目を削除する方法はありますか?リストアイテムの削除時にVueコンポーネントをリフレッシュする方法は?
ここでの使用例です。 Markdownエディタを備えたオンラインフォーラムを考えてみましょう。 Vueインスタンスがあり、そのデータはサーバーからフェッチされた保存コメントのリストです。これらのコメントはMarkdownsに書かれているはずです。
編集やプレビューを容易にするために、コンポーネントのリストも用意されています。各コンポーネントには、編集可能な入力バッファとプレビューセクションがあります。 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()
を試しましたが、それは役に立ちませんでした。
ありがとうございます。それは完全に動作します。ドキュメントで ':key'の使い方を調べることができる場所を知っていますか? – user740006