使用vue实现grid-layout功能实例代码

2020-06-16 05:48:32易采站长站整理

1.先clone项目到本地。

2.

git reset --hard commit
命令可以使当前head指向某个commit。

完成html的基本布局

点击复制按钮来复制整个commit id。然后在项目根路径下运行

git reset 
。用浏览器打开index.html来预览效果,该插件的html主要结果如下:


<!-- 节点容器 -->
<div class="dragrid">
<!-- 可拖拽的节点,使用translate控制位移 -->
<div class="dragrid-item" style="transform: translate(0px, 0px)">
<!-- 通过slot可以插入动态内容 -->
<div class="dragrid-item-content">

</div>
<!-- 拖拽句柄 -->
<div class="dragrid-drag-bar"></div>
<!-- 缩放句柄 -->
<div class="dragrid-resize-bar"></div>
</div>
</div>

使用vue完成nodes简单排版

先切换commit,安装需要的包,运行如下命令:


git reset --hard 83842ea107e7d819761f25bf06bfc545102b2944
npm install
<!-- 启动,端口为7777,在package.json中可以修改 -->
npm start

这一步一个是搭建环境,这个直接看webpack.config.js配置文件就可以了。

另一个就是节点的排版(layout),主要思路是把节点容器看成一个网格,每个节点就可以通过横坐标(x)和纵坐标(y)来控制节点的位置,左上角坐标为(0, 0);通过宽(w)和高(h)来控制节点大小;每个节点还必须有一个唯一的id。这样节点node的数据结构就为:


{
id: "uuid",
x: 0,
y: 0,
w: 6,
h: 8
}

其中w和h的值为所占网格的格数,例如容器是24格,且宽度为960px,每格宽度就为40px,则上面节点渲染为240px * 320px, 且在容器左上角。

来看一下dragrid.vue与之对应的逻辑:


computed: {
cfg() {
let cfg = Object.assign({}, config);
cfg.cellW = Math.floor(this.containerWidth / cfg.col);
cfg.cellH = cfg.cellW; // 1:1
return cfg;
}
},
methods: {
getStyle(node) {
return {
width: node.w * this.cfg.cellW + 'px',
height: node.h * this.cfg.cellH + 'px',
transform: "translate("+ node.x * this.cfg.cellW +"px, "+ node.y * this.cfg.cellH +"px)"
};
}
}

其中cellW、cellH为每个格子的宽和高,这样计算节点的宽和高及位移就很容易了。

完成单个节点的拖拽

拖拽事件

1.使用mousedown、mousemove、mouseup来实现拖拽。

2.这些事件绑定在document上,只需要绑定一次就可以。

执行流程大致如下: