[英]Vue.js, change the Array items order and make that change in the DOM as well
[英]Update array order in Vue.js after DOM change
我有一個基本的Vue.js對象:
var playlist = new Vue({
el : '#playlist',
data : {
entries : [
{ title : 'Oh No' },
{ title : 'Let it Out' },
{ title : 'That\'s Right' },
{ title : 'Jump on Stage' },
{ title : 'This is the Remix' }
]
}
});
HTML:
<div id="playlist">
<div v-for="entry in entries">
{{ entry.title }}
</div>
</div>
我也使用拖放庫(dragula)來允許用戶重新排列#playlist div。
但是,在用戶使用dragula重新排列播放列表后,此更改不會反映在Vue的playlist.entries
,只會在DOM中反映出來。
我已經連接到dragula事件來確定移動元素的起始索引和結束索引。 更新Vue對象以反映新訂單的正確方法是什么?
小提琴: https : //jsfiddle.net/cxx77kco/5/
Vue的v-for
不跟蹤它創建的DOM元素的修改。 因此,當dragula通知您更改時,您需要更新模型。 這是一個工作小提琴: https : //jsfiddle.net/hsnvweov/
var playlist = new Vue({
el : '#playlist',
data : {
entries : [
{ title : 'Oh No' },
{ title : 'Let it Out' },
{ title : 'That\'s Right' },
{ title : 'Jump on Stage' },
{ title : 'This is the Remix' }
]
},
ready: function() {
var self = this;
var from = null;
var drake = dragula([document.querySelector('#playlist')]);
drake.on('drag', function(element, source) {
var index = [].indexOf.call(element.parentNode.children, element);
console.log('drag from', index, element, source);
from = index;
})
drake.on('drop', function(element, target, source, sibling) {
var index = [].indexOf.call(element.parentNode.children, element)
console.log('drop to', index, element, target, source, sibling);
self.entries.splice(index, 0, self.entries.splice(from, 1)[0]);
console.log('Vue thinks order is:', playlist.entries.map(e => e.title ).join(', ')
);
})
}
});
我創建了一個完成這項工作的Vue指令。
它與v-for指令完全相同,並且與底層viewmodel數組同步添加拖放功能:
Syntaxe:
<div v-dragable-for="element in list">{{element.name}}</div>
Github存儲庫: Vue.Dragable.For
vue-dragula自動完成,更易於使用。 https://github.com/Astray-git/vue-dragula
你不能只使用$ remove和$ set方法嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.