index.vue 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. <template>
  2. <div class="container">
  3. <div class="left-board">
  4. <div class="logo-wrapper">
  5. <div class="logo">
  6. <img :src="logo" alt="logo"> Form Generator
  7. <a class="github" href="https://github.com/JakHuang/form-generator" target="_blank">
  8. <img src="https://github.githubassets.com/pinned-octocat.svg" alt>
  9. </a>
  10. </div>
  11. </div>
  12. <el-scrollbar class="left-scrollbar">
  13. <div class="components-list">
  14. <div v-for="(item, listIndex) in leftComponents" :key="listIndex">
  15. <div class="components-title">
  16. <svg-icon icon-class="component" />
  17. {{ item.title }}
  18. </div>
  19. <draggable
  20. class="components-draggable"
  21. :list="item.list"
  22. :group="{ name: 'componentsGroup', pull: 'clone', put: false }"
  23. :clone="cloneComponent"
  24. draggable=".components-item"
  25. :sort="false"
  26. @end="onEnd"
  27. >
  28. <div
  29. v-for="(element, index) in item.list"
  30. :key="index"
  31. class="components-item"
  32. @click="addComponent(element)"
  33. >
  34. <div class="components-body">
  35. <svg-icon :icon-class="element.__config__.tagIcon" />
  36. {{ element.__config__.label }}
  37. </div>
  38. </div>
  39. </draggable>
  40. </div>
  41. </div>
  42. </el-scrollbar>
  43. </div>
  44. <div class="center-board">
  45. <div class="action-bar">
  46. <!-- <el-button icon="el-icon-video-play" type="text" @click="run">-->
  47. <!-- 运行-->
  48. <!-- </el-button>-->
  49. <el-button icon="el-icon-view" type="text" @click="showJson">
  50. 查看json
  51. </el-button>
  52. <el-button icon="el-icon-download" type="text" @click="download">
  53. 导出vue文件
  54. </el-button>
  55. <el-button class="copy-btn-main" icon="el-icon-document-copy" type="text" @click="copy">
  56. 复制代码
  57. </el-button>
  58. <el-button class="delete-btn" icon="el-icon-delete" type="text" @click="empty">
  59. 清空
  60. </el-button>
  61. </div>
  62. <el-scrollbar class="center-scrollbar">
  63. <el-row class="center-board-row" :gutter="formConf.gutter">
  64. <el-form
  65. :size="formConf.size"
  66. :label-position="formConf.labelPosition"
  67. :disabled="formConf.disabled"
  68. :label-width="formConf.labelWidth + 'px'"
  69. >
  70. <draggable class="drawing-board" :list="drawingList" :animation="340" group="componentsGroup">
  71. <draggable-item
  72. v-for="(item, index) in drawingList"
  73. :key="item.renderKey"
  74. :drawing-list="drawingList"
  75. :current-item="item"
  76. :index="index"
  77. :active-id="activeId"
  78. :form-conf="formConf"
  79. @activeItem="activeFormItem"
  80. @copyItem="drawingItemCopy"
  81. @deleteItem="drawingItemDelete"
  82. />
  83. </draggable>
  84. <div v-show="!drawingList.length" class="empty-info">
  85. 从左侧拖入或点选组件进行表单设计
  86. </div>
  87. </el-form>
  88. </el-row>
  89. </el-scrollbar>
  90. </div>
  91. <right-panel
  92. :active-data="activeData"
  93. :form-conf="formConf"
  94. :show-field="!!drawingList.length"
  95. @tag-change="tagChange"
  96. @fetch-data="fetchData"
  97. />
  98. <form-drawer
  99. :visible.sync="drawerVisible"
  100. :form-data="formData"
  101. size="100%"
  102. :generate-conf="generateConf"
  103. />
  104. <json-drawer
  105. size="60%"
  106. :visible.sync="jsonDrawerVisible"
  107. :json-str="JSON.stringify(formData)"
  108. @refresh="refreshJson"
  109. />
  110. <code-type-dialog
  111. :visible.sync="dialogVisible"
  112. title="选择生成类型"
  113. :show-file-name="showFileName"
  114. @confirm="generate"
  115. />
  116. <input id="copyNode" type="hidden">
  117. </div>
  118. </template>
  119. <script>
  120. import draggable from 'vuedraggable'
  121. import { debounce } from 'throttle-debounce'
  122. import { saveAs } from 'file-saver'
  123. import ClipboardJS from 'clipboard'
  124. import render from '@/components/render/render'
  125. import FormDrawer from './FormDrawer'
  126. import JsonDrawer from './JsonDrawer'
  127. import RightPanel from './RightPanel'
  128. import {
  129. inputComponents, selectComponents, layoutComponents, formConf
  130. } from '@/components/generator/config'
  131. import {
  132. beautifierConf, titleCase, deepClone
  133. } from '@/utils'
  134. import {
  135. makeUpHtml, vueTemplate, vueScript, cssStyle
  136. } from '@/components/generator/html'
  137. import { makeUpJs } from '@/components/generator/js'
  138. import { makeUpCss } from '@/components/generator/css'
  139. import drawingDefalut from '@/components/generator/drawingDefalut'
  140. import logo from '@/assets/logo/logo.png'
  141. import CodeTypeDialog from './CodeTypeDialog'
  142. import DraggableItem from './DraggableItem'
  143. import {
  144. getDrawingList, saveDrawingList, getIdGlobal, saveIdGlobal, getFormConf
  145. } from '@/utils/db'
  146. import loadBeautifier from '@/utils/loadBeautifier'
  147. let beautifier
  148. const emptyActiveData = { style: {}, autosize: {} }
  149. let oldActiveId
  150. let tempActiveData
  151. const drawingListInDB = getDrawingList()
  152. const formConfInDB = getFormConf()
  153. const idGlobal = getIdGlobal()
  154. export default {
  155. name: "InfraBuild",
  156. components: {
  157. draggable,
  158. render,
  159. FormDrawer,
  160. JsonDrawer,
  161. RightPanel,
  162. CodeTypeDialog,
  163. DraggableItem
  164. },
  165. data() {
  166. return {
  167. logo,
  168. idGlobal,
  169. formConf,
  170. inputComponents,
  171. selectComponents,
  172. layoutComponents,
  173. labelWidth: 100,
  174. drawingList: drawingDefalut,
  175. drawingData: {},
  176. activeId: drawingDefalut[0].formId,
  177. drawerVisible: false,
  178. formData: {},
  179. dialogVisible: false,
  180. jsonDrawerVisible: false,
  181. generateConf: null,
  182. showFileName: false,
  183. activeData: drawingDefalut[0],
  184. saveDrawingListDebounce: debounce(340, saveDrawingList),
  185. saveIdGlobalDebounce: debounce(340, saveIdGlobal),
  186. leftComponents: [
  187. {
  188. title: '输入型组件',
  189. list: inputComponents
  190. },
  191. {
  192. title: '选择型组件',
  193. list: selectComponents
  194. },
  195. {
  196. title: '布局型组件',
  197. list: layoutComponents
  198. }
  199. ]
  200. }
  201. },
  202. computed: {
  203. },
  204. watch: {
  205. // eslint-disable-next-line func-names
  206. 'activeData.__config__.label': function (val, oldVal) {
  207. if (
  208. this.activeData.placeholder === undefined
  209. || !this.activeData.__config__.tag
  210. || oldActiveId !== this.activeId
  211. ) {
  212. return
  213. }
  214. this.activeData.placeholder = this.activeData.placeholder.replace(oldVal, '') + val
  215. },
  216. activeId: {
  217. handler(val) {
  218. oldActiveId = val
  219. },
  220. immediate: true
  221. },
  222. drawingList: {
  223. handler(val) {
  224. this.saveDrawingListDebounce(val)
  225. if (val.length === 0) this.idGlobal = 100
  226. },
  227. deep: true
  228. },
  229. idGlobal: {
  230. handler(val) {
  231. this.saveIdGlobalDebounce(val)
  232. },
  233. immediate: true
  234. }
  235. },
  236. mounted() {
  237. if (Array.isArray(drawingListInDB) && drawingListInDB.length > 0) {
  238. this.drawingList = drawingListInDB
  239. } else {
  240. this.drawingList = drawingDefalut
  241. }
  242. this.activeFormItem(this.drawingList[0])
  243. if (formConfInDB) {
  244. this.formConf = formConfInDB
  245. }
  246. loadBeautifier(btf => {
  247. beautifier = btf
  248. })
  249. const clipboard = new ClipboardJS('#copyNode', {
  250. text: trigger => {
  251. const codeStr = this.generateCode()
  252. this.$notify({
  253. title: '成功',
  254. message: '代码已复制到剪切板,可粘贴。',
  255. type: 'success'
  256. })
  257. return codeStr
  258. }
  259. })
  260. clipboard.on('error', e => {
  261. this.$message.error('代码复制失败')
  262. })
  263. },
  264. methods: {
  265. setObjectValueReduce(obj, strKeys, data) {
  266. const arr = strKeys.split('.')
  267. arr.reduce((pre, item, i) => {
  268. if (arr.length === i + 1) {
  269. pre[item] = data
  270. } else if (pre[item]===undefined) {
  271. pre[item] = {}
  272. }
  273. return pre[item]
  274. }, obj)
  275. },
  276. setRespData(component, resp) {
  277. const { dataPath, renderKey, dataConsumer } = component.__config__
  278. if (!dataPath || !dataConsumer) return
  279. const respData = dataPath.split('.').reduce((pre, item) => pre[item], resp)
  280. // 将请求回来的数据,赋值到指定属性。
  281. // 以el-tabel为例,根据Element文档,应该将数据赋值给el-tabel的data属性,所以dataConsumer的值应为'data';
  282. // 此时赋值代码可写成 component[dataConsumer] = respData;
  283. // 但为支持更深层级的赋值(如:dataConsumer的值为'options.data'),使用setObjectValueReduce
  284. this.setObjectValueReduce(component, dataConsumer, respData)
  285. const i = this.drawingList.findIndex(item => item.__config__.renderKey === renderKey)
  286. if (i > -1) this.$set(this.drawingList, i, component)
  287. },
  288. fetchData(component) {
  289. const { dataType, method, url } = component.__config__
  290. if (dataType === 'dynamic' && method && url) {
  291. this.setLoading(component, true)
  292. this.$axios({
  293. method,
  294. url
  295. }).then(resp => {
  296. this.setLoading(component, false)
  297. this.setRespData(component, resp)
  298. })
  299. }
  300. },
  301. setLoading(component, val) {
  302. const { directives } = component
  303. if (Array.isArray(directives)) {
  304. const t = directives.find(d => d.name === 'loading')
  305. if (t) t.value = val
  306. }
  307. },
  308. activeFormItem(currentItem) {
  309. this.activeData = currentItem
  310. this.activeId = currentItem.__config__.formId
  311. },
  312. onEnd(obj) {
  313. if (obj.from !== obj.to) {
  314. this.fetchData(tempActiveData)
  315. this.activeData = tempActiveData
  316. this.activeId = this.idGlobal
  317. }
  318. },
  319. addComponent(item) {
  320. const clone = this.cloneComponent(item)
  321. this.fetchData(clone)
  322. this.drawingList.push(clone)
  323. this.activeFormItem(clone)
  324. },
  325. cloneComponent(origin) {
  326. const clone = deepClone(origin)
  327. const config = clone.__config__
  328. config.span = this.formConf.span // 生成代码时,会根据span做精简判断
  329. this.createIdAndKey(clone)
  330. clone.placeholder !== undefined && (clone.placeholder += config.label)
  331. tempActiveData = clone
  332. return tempActiveData
  333. },
  334. createIdAndKey(item) {
  335. const config = item.__config__
  336. config.formId = ++this.idGlobal
  337. config.renderKey = `${config.formId}${+new Date()}` // 改变renderKey后可以实现强制更新组件
  338. if (config.layout === 'colFormItem') {
  339. item.__vModel__ = `field${this.idGlobal}`
  340. } else if (config.layout === 'rowFormItem') {
  341. config.componentName = `row${this.idGlobal}`
  342. !Array.isArray(config.children) && (config.children = [])
  343. delete config.label // rowFormItem无需配置label属性
  344. }
  345. if (Array.isArray(config.children)) {
  346. config.children = config.children.map(childItem => this.createIdAndKey(childItem))
  347. }
  348. return item
  349. },
  350. AssembleFormData() {
  351. this.formData = {
  352. fields: deepClone(this.drawingList),
  353. ...this.formConf
  354. }
  355. },
  356. generate(data) {
  357. const func = this[`exec${titleCase(this.operationType)}`]
  358. this.generateConf = data
  359. func && func(data)
  360. },
  361. execRun(data) {
  362. this.AssembleFormData()
  363. this.drawerVisible = true
  364. },
  365. execDownload(data) {
  366. const codeStr = this.generateCode()
  367. const blob = new Blob([codeStr], { type: 'text/plain;charset=utf-8' })
  368. saveAs(blob, data.fileName)
  369. },
  370. execCopy(data) {
  371. document.getElementById('copyNode').click()
  372. },
  373. empty() {
  374. this.$confirm('确定要清空所有组件吗?', '提示', { type: 'warning' }).then(
  375. () => {
  376. this.drawingList = []
  377. this.idGlobal = 100
  378. }).catch(() => {});
  379. },
  380. drawingItemCopy(item, list) {
  381. let clone = deepClone(item)
  382. clone = this.createIdAndKey(clone)
  383. list.push(clone)
  384. this.activeFormItem(clone)
  385. },
  386. drawingItemDelete(index, list) {
  387. list.splice(index, 1)
  388. this.$nextTick(() => {
  389. const len = this.drawingList.length
  390. if (len) {
  391. this.activeFormItem(this.drawingList[len - 1])
  392. }
  393. })
  394. },
  395. generateCode() {
  396. const { type } = this.generateConf
  397. this.AssembleFormData()
  398. const script = vueScript(makeUpJs(this.formData, type))
  399. const html = vueTemplate(makeUpHtml(this.formData, type))
  400. const css = cssStyle(makeUpCss(this.formData))
  401. return beautifier.html(html + script + css, beautifierConf.html)
  402. },
  403. showJson() {
  404. this.AssembleFormData()
  405. this.jsonDrawerVisible = true
  406. },
  407. download() {
  408. this.dialogVisible = true
  409. this.showFileName = true
  410. this.operationType = 'download'
  411. },
  412. run() {
  413. this.dialogVisible = true
  414. this.showFileName = false
  415. this.operationType = 'run'
  416. },
  417. copy() {
  418. this.dialogVisible = true
  419. this.showFileName = false
  420. this.operationType = 'copy'
  421. },
  422. tagChange(newTag) {
  423. newTag = this.cloneComponent(newTag)
  424. const config = newTag.__config__
  425. newTag.__vModel__ = this.activeData.__vModel__
  426. config.formId = this.activeId
  427. config.span = this.activeData.__config__.span
  428. this.activeData.__config__.tag = config.tag
  429. this.activeData.__config__.tagIcon = config.tagIcon
  430. this.activeData.__config__.document = config.document
  431. if (typeof this.activeData.__config__.defaultValue === typeof config.defaultValue) {
  432. config.defaultValue = this.activeData.__config__.defaultValue
  433. }
  434. Object.keys(newTag).forEach(key => {
  435. if (this.activeData[key] !== undefined) {
  436. newTag[key] = this.activeData[key]
  437. }
  438. })
  439. this.activeData = newTag
  440. this.updateDrawingList(newTag, this.drawingList)
  441. },
  442. updateDrawingList(newTag, list) {
  443. const index = list.findIndex(item => item.__config__.formId === this.activeId)
  444. if (index > -1) {
  445. list.splice(index, 1, newTag)
  446. } else {
  447. list.forEach(item => {
  448. if (Array.isArray(item.__config__.children)) this.updateDrawingList(newTag, item.__config__.children)
  449. })
  450. }
  451. },
  452. refreshJson(data) {
  453. this.drawingList = deepClone(data.fields)
  454. delete data.fields
  455. this.formConf = data
  456. }
  457. }
  458. }
  459. </script>
  460. <style lang='scss'>
  461. @import '@/styles/home';
  462. </style>