sortablejs + vue的拖拽效果 列表个数不固定 刷新后保持拖拽后的效果
程序员文章站
2022-07-10 21:26:42
{{list.tittle}}
<template> <div class="hello"> <div v-for="(list, index) in merge" :key="index" class="box" :id="`box-${index}`"> <h1>{{list.tittle}}</h1> <ul :id="`id-${index}`" v-for="(item, indexitem) in list.list" :key="indexitem"> <li>{{item.name}}</li> </ul> </div> </div> </template> <script> import sortable from 'sortablejs'; export default { name: 'helloworld', data() { return { //state 里面的name分别对应的是列表里面的标题 //state里面的1 2 3和list里面的 1 2 3 的关系是:类别归属关系 // 标题1 下面列表对应的分别是 列表1,列表2,列表3 state: { 1: "标题1", 2: "标题2", 3: "标题3", 4: "标题4", 5: "标题5" }, list: { 1: [{ id: 1, name: "1、列表1" }, { id: 2, name: "2、列表2" }, { id: 3, name: "3、列表3" }, ], 2: [{ id: 4, name: "4、列表4" }, { id: 5, name: "5、列表5" }, { id: 6, name: "6、列表6" }, ], 3: [{ id: 7, name: '列表7' }] }, merge: [] // 把state 和 list 合并在一个数组里面 } }, created() { // 看缓存有没有list数据 有就读取缓存 没有就合并获取的数据 逻辑顺序 1 if (localstorage.getitem('movelocalstoragelist')) { this.merge = json.parse(localstorage.getitem('movelocalstoragelist')) } else { this.merge = this.datamerge() // 合并数据 } }, methods: { /** * 处理数据 把标题和内容合并到一个数组里面 逻辑顺序 2 */ datamerge() { let { state, list } = { ...this } let arr = [] for (let i in state) { arr.push({ tittle: state[i], list: list[i] || [] }) } return arr }, /** * 通过id获取dom */ _$id(id) { return document.getelementbyid(id) }, /** * 通过dom 获取数据数组 并存储到缓存 逻辑顺序 4 */ getdomdata() { let doms = document.getelementsbyclassname('hello')[0].children // console.log(doms) let merge = [] for (let i = 0; i < doms.length; i++) { let tittle = '' let list = [] let uls = doms[i].children for (let k = 0; k < uls.length; k++) { if (k == 0) { tittle = uls[k].innerhtml // console.log('tittle', tittle) } else { let name = uls[k].children[0].innerhtml // console.log('name', name) list.push({ name: name }) } } merge.push({ tittle: tittle, list: list }) } // console.log(merge) localstorage.setitem('movelocalstoragelist', json.stringify(merge)) }, /** * 新建sortable 逻辑顺序 3 */ createdsortable() { let _this = this for (let i = 0; i < this.merge.length; i++) { let item = this.merge[i].list let _id = `box-${i}` new sortable(this._$id(_id), { group: 'shared', // set both lists to same group animation: 150, onend(evt) { // console.log(evt, evt.oldindex, evt.newindex) _this.getdomdata() } }) } } }, mounted() { this.createdsortable() } } </script> <!-- add "scoped" attribute to limit css to this component only --> <style scoped> * { margin: 0; padding: 0; list-style: none; } .hello { display: flex; } .hello .box { width: 30%; margin-left: 20px; border: 1px solid blue; padding: 10px; } .hello ul li { border: 1px solid red; padding: 20px; margin-top: 10px; } </style>
video演示地址:
https://cengjingdeshuige.oss-cn-beijing.aliyuncs.com/video/e127a65dac466466cc02a4b1642545a4.mp4
git仓库地址 demo