最近因项目需求,需要开发一个可以拖拽布局的功能。本人刚接触vue不久,但已经被其强大的功能所吸引,再加上vue的组件化思想很契合项目需求,所以决定使用vue开发。网上搜索vue实现拖拽布局的插件许多,最后选择了容易上手的vue-grid-layout插件,废话太多了,开始整干货。
github地址:vue-grid-layout
首先安装插件
npm install vue-grid-layout --save
然后在页面中引入
import VueGridLayout from 'vue-grid-layout'
const grid-layout = VueGridLayout.GridLayout
const grid-item = VueGridLayout.GridItem
grid-layou代表布局区域,和栅格系统差不多,主要有两个属性需要关注:col-num代表栅格的列数 ,row-height代表每一行的高度。其余的属性可更加文档自行查看。
grid-item代表区域中的每一个元素,主要的属性有五个:x标识元素位于第几列,y标识元素位于第几行,w代表元素的初始宽度,也就数占了几列, h 代表元素的初始高度度,也就数占了几行,i为每个元素的id。
因为想要实现一个左侧展示可选组件,右侧进行拖拽布局的功能,先看一下效果
思路是引入两个grid-layout,左侧的只放组件,右侧的负责最终布局,点击左侧的组件可以添加到右侧的窗体区,双击右侧的组件进行删除。所以需要两个json文件,一个resourcesdata.json存储组件信息,一个layoutdata.json存储布局信息。
resourcesdata.json
[{
"x": 0,
"y": 0,
"w": 12,
"h": 2,
"i": 0,
"Component": "barChart",
"IsResource": true
},
{
"x": 0,
"y": 0,
"w": 12,
"h": 2,
"i": 2,
"Component": "lineChart",
"IsResource": true
},
{
"x": 0,
"y": 0,
"w": 12,
"h": 2,
"i": 3,
"Component": "parChart",
"IsResource": true
},
{
"x": 0,
"y": 0,
"w": 12,
"h": 2,
"i": 4,
"Component": "mapChart",
"IsResource": true
},
{
"x": 0,
"y": 0,
"w": 12,
"h": 2,
"i": 5,
"Component": "borderChart",
"IsResource": true
}
]
layoutdata.json
[{"x":0,"y":0,"w":2,"h":2,"i":0,"Component":"borderChart","IsResource":true,"moved":false},{"x":2,"y":0,"w":2,"h":2,"i":1,"Component":"borderChart","IsResource":true,"moved":false},{"x":4,"y":0,"w":2,"h":2,"i":2,"Component":"borderChart","IsResource":true,"moved":false},{"x":6,"y":0,"w":2,"h":2,"i":3,"Component":"borderChart","IsResource":true,"moved":false},{"x":8,"y":0,"w":2,"h":2,"i":4,"Component":"borderChart","IsResource":true,"moved":false},{"x":10,"y":0,"w":2,"h":2,"i":5,"Component":"borderChart","IsResource":true,"moved":false},{"x":0,"y":2,"w":2,"h":2,"i":6,"Component":"borderChart","IsResource":true,"moved":false},{"x":2,"y":2,"w":2,"h":2,"i":7,"Component":"borderChart","IsResource":true,"moved":false},{"x":4,"y":2,"w":2,"h":2,"i":8,"Component":"borderChart","IsResource":true,"moved":false},{"x":6,"y":2,"w":2,"h":2,"i":9,"Component":"borderChart","IsResource":true,"moved":false},{"x":8,"y":2,"w":2,"h":2,"i":10,"Component":"borderChart","IsResource":true,"moved":false},{"x":10,"y":2,"w":2,"h":2,"i":11,"Component":"borderChart","IsResource":true,"moved":false},{"x":0,"y":4,"w":2,"h":2,"i":12,"Component":"borderChart","IsResource":true,"moved":false},{"x":2,"y":4,"w":2,"h":2,"i":13,"Component":"borderChart","IsResource":true,"moved":false}]
两个数据格式基本一致,增加量Component属性代表自定义组件的名称,使用for循环构建组件。
组件区代码
组件区(单击添加)
窗体区代码
窗体区(高度超出蓝色线框生成的页面将会产生滚动条)
保存布局
没时间了,先放一下最终效果,后期继续更新
以下为相关参考,感谢分享
https://segmentfault.com/a/1190000020748297
https://blog.csdn.net/csl125/article/details/89245267
https://blog.csdn.net/weixin_42416812/article/details/100031977