我正在尝试使用 vuejs 和 jquery ui 创建一个具有删除功能的可排序列表,我得到以下结果
请检查以下jsfiddle
https://jsfiddle.net/reda84/7ojgvwdw/
删除功能正在工作,但是一旦开始排序,删除功能就不再正常工作,特别是对于已排序的项目及其下面的项目。
如果我将两个组件组合成一个,就像下面的 fiddle 一样,它可以正常工作,但我不希望这样,因为原始应用程序更复杂,组件更复杂,我想将它分开。
https://jsfiddle.net/reda84/jv7zhz1u/
TLDR: 这是代码
var listItem = Vue.extend({
template: '<li class="ui-state-default">{{item.title}} {{item.id}} <span v-on:click="remove(item)"> x </span></li>',
props: {
item: Object
},
methods: {
remove: function(item) {
this.$dispatch('remove-item', item)
}
}
});
var sortableList = Vue.extend({
template: '<ul id="sortable"><list-item v-for="item in list" :item="item" class="ui-state-default"></list-item></ul>',
data: function() {
return {
list: [{ id: 1, title: "Item"},
{ id: 2, title: "Item"},
{ id: 3, title: "Item"}]
}
},
events: {
"remove-item": function(item) {
var index = this.list.indexOf(item)
this.list.splice(index, 1);
}
},
components: {
listItem
},
});
new Vue({
el: 'body',
ready: function() {
$("#sortable").sortable();
$("#sortable").disableSelection();
},
components: {
sortableList
},
});
最佳答案
看起来 v-for
和 sortable
不能同时直接位于 vue 组件上。我的猜测是,当 Vue 和 JQuery 都尝试管理 li
元素时,它们会发生冲突。
如果该组件是 v-for
的子组件,则该组件有效。这是updated fiddle ,以及一个工作代码片段:
Vue.component('list-item', {
template: '#list-item',
props: {
item: Object
},
methods: {
remove: function (item) {
this.$emit('remove-item', item)
}
}
});
Vue.component('sortable-list', {
template: '#sortable-list',
data: function () {
return {
list: [{
id: 1,
title: "Item"
}, {
id: 2,
title: "Item"
}, {
id: 3,
title: "Item"
}]
}
},
methods: {
"removeItem": function (item) {
var index = this.list.indexOf(item)
this.list.splice(index, 1);
}
}
});
new Vue({
el: '#app',
mounted: function () {
$("#sortable").sortable();
$("#sortable").disableSelection();
}
});
#sortable {
list-style-type: none;
margin: 0;
padding: 0;
width: 60%;
}
#sortable li {
font-family: Arial;
margin: 0 3px 3px 3px;
padding: 0.4em;
padding-left: 1.5em;
font-size: 1.4em;
height: 18px;
}
#sortable li span {
float: right;
cursor: pointer
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.4/vue.js"></script>
<div id="app">
<sortable-list></sortable-list>
</div>
<template id="list-item">
<div class="ui-state-default">
{{item.title}} {{item.id}}
<span v-on:click="remove(item)"> x </span>
</div>
</template>
<template id="sortable-list">
<ul id="sortable">
<li v-for="item in list">
<list-item :item="item"
class="ui-state-default"
@remove-item="removeItem">
</list-item>
</li>
</ul>
</template>
注意:该代码段已更新为使用 Vue 2.0 语法。
关于jquery - Vuejs 与 JQuery UI 可排序问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35535489/