插件 sortablejs
- 用于可重新排序拖放列表的JavaScript库;
- 关键链接:npm 地址 Github 地址
安装
npm i sortablejs
引入
import Sortable from "sortablejs"
HTML
<ul id="items"><li>item 1</li><li>item 2</li><li>item 3</li><li>item 4</li><li>item 5</li>
</ul>
<div id="items"><div>item 1</div><div>item 2</div><div>item 3</div><div>item 4</div><div>item 5</div>
</div>
初始化
- 代码第
1
行,注意是获取父元素。但可拖动的是其子元素 - 代码第
2
行,第二个参数有很多属性和回调方法:如:animation
, onStart
, onEnd
。完整代码 中使用方法 onEnd
,如想了解更多参数,可在此查看 Options;
let el = document.getElementById('items');
Sortable.create(el, {});
效果

完成代码
<template><div class="sortabele-main"><ul id="items"><li>item 1</li><li>item 2</li><li>item 3</li><li>item 4</li><li>item 5</li></ul></div>
</template><script>
import Sortable from "sortablejs"export default {methods: {initSortable() {let el = document.getElementById('items');Sortable.create(el, {onEnd: ({ oldIndex, newIndex }) => {console.log(newIndex, oldIndex);}});}},mounted() {this.initSortable();}
}
</script><style lang="stylus" scoped>
.sortabele-main {padding: 20px;ul {list-style-type: none;li {width: 90px;height: 30px;line-height: 30px;text-align: center;background: #ccc;cursor: pointer;margin: 8px;}}
}
</style>