vue-grid-layout+component 实现动态布局

8,911 阅读2分钟

是什么?

git 地址: vue-grid-layout

官方 demo

代码

在线演示

常用参数解析

GridLayout

参数 含义 数据类型
colNum 将一行分为多少块 数字 默认 12
rowHeight 行高 数字 默认是单位是 px
isDraggable 是否可以拖拽 boolean
isResizable 是否可以改变大小 boolean
responsive 是否是响应式的 boolean

GridItem

参数 含义 类型
i id 类型不限
x 第几列 数字
y 第几行 数字
w 占几块 数字
h 高度 ,最后算出的元素高度是 h*rowHeight 数字

主要代码

定义一个默认的布局

var testLayout = [
  {x: 0,y: 0,w: 6,h: 5,i: "0",component: "test1"},//0列0行 宽为5块,高为5*rowHeight
  {x: 6, y: 0, w: 6, h: 5, i: "1", component: "test2" },// 列为6(因为上一块的宽度是6)
  {x: 0,y: 5,w: 12,h: 10,i: "2",component: "test3"},//自己算一算吧
  {x: 0,y: 15,w: 12,h: 10,i: "3",component: "test4"}
];

生成布局

// 最外大的grid,绑定了testLayout的值,这样testLayout 会随着用户的拖拽放大缩小改变
// 可以参考官方的实例
<grid-layout
          :layout.sync="testLayout"
          :col-num="12"
          :row-height="55"
          :is-draggable="draggable"
          :is-resizable="resizable"
          :auto-size="true"
          :responsive="responsive"
        >
        // 遍历testLayout生成item
          <grid-item
            v-for="item in testLayout"
            :x="item.x"
            :y="item.y"
            :w="item.w"
            :h="item.h"
            :i="item.i"
            :key="item.key"
          >
            <div class="assistor">
             // 定义一个关闭按钮实现删除当前的
              <div class="close-icon" @click="deleteComponent(item.i)">
                <i class="el-icon-close"></i>
              </div>
              <h4 style="margin-bottom:10px">{{item.title}}</h4>
              // 这里使用component来显示组件。
              <component :is="item.component" style="padding-bottom:20px"></component>
            </div>
          </grid-item>
        </grid-layout>

css 样式

定义整个布局的背景颜色

.vue-grid-layout {
  position: relative;
  background: #fff;
}

定义每一个 item 的样式

.vue-grid-item{

}

GridItem 内部元素的样式
这里在 grid-item 内部加入一个 assistor,是因为如果 grid-item 内部元素的大小过大会出现滚动条
这里将 border 加在 assistor 上,
当然你也可以加在.vue-grid-item 上,但是如果你需要动态的增加组件的话,在增加的时候 boder 会加不上。

.assistor {
  height: 100%;
  overflow-y: scroll;
  padding: 10px;
  border: 1px solid rgb(224, 219, 219);
}

增加一个关闭的按钮

.close-icon {
  float: right;
  position: absolute;
  text-align: right;
  right: 0px;
  top: 0px;
  z-index: 200;
}

动态增减的实现思路

其实就是对 layout 进行操作
最简单的加法,直接占满第一行

this.testLayout.push({
        x: 0,
        y: 0,
        w: 12,
        h: 5,
        i: this.layout.length,
        name: "test5"
      });

减法的话,直接根据传进来的 id 删除即可

deleteComponent(id){
  this.testLayout = this.testLayout.filter(
      item =>item.id===id
    );
}

数据库

直接将 testLayout 存入数据库即可。

本文使用 mdnice 排版