持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第2天,点击查看活动详情
开篇
上篇我们把基础的布局做好了。这次开发基础布局组件。
思路
- 添加vue-grid-layout组件
- 配置文件描述
- 拖拽事件
添加布局组件
Vue Grid Layout npm添加依赖包:
npm install vue-grid-layout --save
基本使用:
https://jbaysolutions.github.io/vue-grid-layout/zh/guide/01-basic.html
添加遇到的问题
-
运行项目的时候报了下面的警告,vue 报错 { parser: “babylon“ } is deprecated; we now treat it as { parser: “babel“ } 解决方法:找到 node_modules\vue-loader\lib\template-compiler\index.js 搜索“parser”然后把 babylon 修改为babel 即可.
-
修改完上一个问题之后,又报错了,Module parse failed: Unexpected token (10332:31) at build。
error in ./node_modules/vue-grid-layout/dist/vue-grid-layout.common.js Module parse failed: Unexpected token (10332:31) You may need an appropriate loader to handle this file type. | subModification.prepareStates(modifiers); | state.subModification = subModification; | subModification.startAll({ ...arg @ ./node_modules/babel-loader/lib!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./src/views/report/reportPreview.vue 75:0-44 @ ./src/views/report/reportPreview.vue @ ./src/router/modules/quote.js @ ./src/router/index.js @ ./src/router/permission.js @ ./src/main.js @ multi (webpack)-dev-server/client?http://localhost:8081 webpack/hot/dev-server babel-polyfill ./src/main.js解决方法:就是固定版本2.3.7. 参考地址:github.com/jbaysolutio…
-
添加vue-grid-layout的样式。要不然我们拖拽之后,是没有背景颜色和边框样式的。
.vue-grid-item { background: #ccc; border: 1px solid #000; }
配置文件描述
layout.js 控制布局文件的描述文件。layoutId布局组件唯一标识。components组件的描述文件。其余的是vue-grid-layout,所需要的描述文件。如下:
import { uniqueId } from "lodash";
class Layout {
constructor() {
this.layoutConfig = {
layoutId: "",
x: 0,
y: 0,
w: 2,
h: 2,
i: "0",
static: false,
components: {} //id:{} 组件信息
};
}
getLayoutConfig(layoutId) {
let layoutConfig = {};
layoutConfig = this.layoutConfig;
return layoutConfig;
}
}
const LayoutConfig = new Layout();
export const getLayoutConfig = () => {
const layoutId = uniqueId("CA_");
return LayoutConfig.getLayoutConfig(layoutId);
};
拖拽事件
- 拖拽事件使用的是原生的dragstart,dragover和drop进行组件的拖拽。使用拖拽event.dataTransfer保存和获取拖拽的数据。
- event.dataTransfer.setData("text/plain", JSON.stringify(data));
- const componentConfig = JSON.parse(event.dataTransfer.getData('text/plain'));
遇到的问题
- drop事件不触发。需要在enter和over处阻止默认行为 stackoverflow.com/questions/2…
- el.dataTransfer.setData无效? chrome不支持.stackoverflow.com/questions/9…
添加控制区域的网格背景
.box-card {
width: 100%;
height: 96vh;
margin-left: 10px;
background-image: linear-gradient(90deg, rgba(0, 0, 0, 0.15) 10%, rgba(0, 0, 0, 0) 10%),linear-gradient(rgba(0, 0, 0, 0.15) 10%, rgba(0, 0, 0, 0) 10%);
background-size: 10px 10px;
}
- background-image:属性为元素设置背景图像。元素的背景占据了元素的全部尺寸,包括内边距和边框,但不包括外边距。默认地,背景图像位于元素的左上角,并在水平和垂直方向上重复。
- background-size:规定背景图像的尺寸
总结
这样就把vue-grid-layout组件导入了。我们可以通过拖拽的形式,从左侧拖拽到中间区域了。下一篇,就是对布局组件的一些列配置了。例如:对组件的删除、静止拖拽、可选中组件等等。