index.vue 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  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. exportDefault, beautifierConf, isNumberStr, titleCase, deepClone
  133. } from '@/utils/index'
  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. components: {
  156. draggable,
  157. render,
  158. FormDrawer,
  159. JsonDrawer,
  160. RightPanel,
  161. CodeTypeDialog,
  162. DraggableItem
  163. },
  164. data() {
  165. return {
  166. logo,
  167. idGlobal,
  168. formConf,
  169. inputComponents,
  170. selectComponents,
  171. layoutComponents,
  172. labelWidth: 100,
  173. drawingList: drawingDefalut,
  174. drawingData: {},
  175. activeId: drawingDefalut[0].formId,
  176. drawerVisible: false,
  177. formData: {},
  178. dialogVisible: false,
  179. jsonDrawerVisible: false,
  180. generateConf: null,
  181. showFileName: false,
  182. activeData: drawingDefalut[0],
  183. saveDrawingListDebounce: debounce(340, saveDrawingList),
  184. saveIdGlobalDebounce: debounce(340, saveIdGlobal),
  185. leftComponents: [
  186. {
  187. title: '输入型组件',
  188. list: inputComponents
  189. },
  190. {
  191. title: '选择型组件',
  192. list: selectComponents
  193. },
  194. {
  195. title: '布局型组件',
  196. list: layoutComponents
  197. }
  198. ]
  199. }
  200. },
  201. computed: {
  202. },
  203. watch: {
  204. // eslint-disable-next-line func-names
  205. 'activeData.__config__.label': function (val, oldVal) {
  206. if (
  207. this.activeData.placeholder === undefined
  208. || !this.activeData.__config__.tag
  209. || oldActiveId !== this.activeId
  210. ) {
  211. return
  212. }
  213. this.activeData.placeholder = this.activeData.placeholder.replace(oldVal, '') + val
  214. },
  215. activeId: {
  216. handler(val) {
  217. oldActiveId = val
  218. },
  219. immediate: true
  220. },
  221. drawingList: {
  222. handler(val) {
  223. this.saveDrawingListDebounce(val)
  224. if (val.length === 0) this.idGlobal = 100
  225. },
  226. deep: true
  227. },
  228. idGlobal: {
  229. handler(val) {
  230. this.saveIdGlobalDebounce(val)
  231. },
  232. immediate: true
  233. }
  234. },
  235. mounted() {
  236. if (Array.isArray(drawingListInDB) && drawingListInDB.length > 0) {
  237. this.drawingList = drawingListInDB
  238. } else {
  239. this.drawingList = drawingDefalut
  240. }
  241. this.activeFormItem(this.drawingList[0])
  242. if (formConfInDB) {
  243. this.formConf = formConfInDB
  244. }
  245. loadBeautifier(btf => {
  246. beautifier = btf
  247. })
  248. const clipboard = new ClipboardJS('#copyNode', {
  249. text: trigger => {
  250. const codeStr = this.generateCode()
  251. this.$notify({
  252. title: '成功',
  253. message: '代码已复制到剪切板,可粘贴。',
  254. type: 'success'
  255. })
  256. return codeStr
  257. }
  258. })
  259. clipboard.on('error', e => {
  260. this.$message.error('代码复制失败')
  261. })
  262. },
  263. methods: {
  264. setObjectValueReduce(obj, strKeys, data) {
  265. const arr = strKeys.split('.')
  266. arr.reduce((pre, item, i) => {
  267. if (arr.length === i + 1) {
  268. pre[item] = data
  269. } else if (pre[item]===undefined) {
  270. pre[item] = {}
  271. }
  272. return pre[item]
  273. }, obj)
  274. },
  275. setRespData(component, resp) {
  276. const { dataPath, renderKey, dataConsumer } = component.__config__
  277. if (!dataPath || !dataConsumer) return
  278. const respData = dataPath.split('.').reduce((pre, item) => pre[item], resp)
  279. // 将请求回来的数据,赋值到指定属性。
  280. // 以el-tabel为例,根据Element文档,应该将数据赋值给el-tabel的data属性,所以dataConsumer的值应为'data';
  281. // 此时赋值代码可写成 component[dataConsumer] = respData;
  282. // 但为支持更深层级的赋值(如:dataConsumer的值为'options.data'),使用setObjectValueReduce
  283. this.setObjectValueReduce(component, dataConsumer, respData)
  284. const i = this.drawingList.findIndex(item => item.__config__.renderKey === renderKey)
  285. if (i > -1) this.$set(this.drawingList, i, component)
  286. },
  287. fetchData(component) {
  288. const { dataType, method, url } = component.__config__
  289. if (dataType === 'dynamic' && method && url) {
  290. this.setLoading(component, true)
  291. this.$axios({
  292. method,
  293. url
  294. }).then(resp => {
  295. this.setLoading(component, false)
  296. this.setRespData(component, resp)
  297. })
  298. }
  299. },
  300. setLoading(component, val) {
  301. const { directives } = component
  302. if (Array.isArray(directives)) {
  303. const t = directives.find(d => d.name === 'loading')
  304. if (t) t.value = val
  305. }
  306. },
  307. activeFormItem(currentItem) {
  308. this.activeData = currentItem
  309. this.activeId = currentItem.__config__.formId
  310. },
  311. onEnd(obj) {
  312. if (obj.from !== obj.to) {
  313. this.fetchData(tempActiveData)
  314. this.activeData = tempActiveData
  315. this.activeId = this.idGlobal
  316. }
  317. },
  318. addComponent(item) {
  319. const clone = this.cloneComponent(item)
  320. this.fetchData(clone)
  321. this.drawingList.push(clone)
  322. this.activeFormItem(clone)
  323. },
  324. cloneComponent(origin) {
  325. const clone = deepClone(origin)
  326. const config = clone.__config__
  327. config.span = this.formConf.span // 生成代码时,会根据span做精简判断
  328. this.createIdAndKey(clone)
  329. clone.placeholder !== undefined && (clone.placeholder += config.label)
  330. tempActiveData = clone
  331. return tempActiveData
  332. },
  333. createIdAndKey(item) {
  334. const config = item.__config__
  335. config.formId = ++this.idGlobal
  336. config.renderKey = `${config.formId}${+new Date()}` // 改变renderKey后可以实现强制更新组件
  337. if (config.layout === 'colFormItem') {
  338. item.__vModel__ = `field${this.idGlobal}`
  339. } else if (config.layout === 'rowFormItem') {
  340. config.componentName = `row${this.idGlobal}`
  341. !Array.isArray(config.children) && (config.children = [])
  342. delete config.label // rowFormItem无需配置label属性
  343. }
  344. if (Array.isArray(config.children)) {
  345. config.children = config.children.map(childItem => this.createIdAndKey(childItem))
  346. }
  347. return item
  348. },
  349. AssembleFormData() {
  350. this.formData = {
  351. fields: deepClone(this.drawingList),
  352. ...this.formConf
  353. }
  354. },
  355. generate(data) {
  356. const func = this[`exec${titleCase(this.operationType)}`]
  357. this.generateConf = data
  358. func && func(data)
  359. },
  360. execRun(data) {
  361. this.AssembleFormData()
  362. this.drawerVisible = true
  363. },
  364. execDownload(data) {
  365. const codeStr = this.generateCode()
  366. const blob = new Blob([codeStr], { type: 'text/plain;charset=utf-8' })
  367. saveAs(blob, data.fileName)
  368. },
  369. execCopy(data) {
  370. document.getElementById('copyNode').click()
  371. },
  372. empty() {
  373. this.$confirm('确定要清空所有组件吗?', '提示', { type: 'warning' }).then(
  374. () => {
  375. this.drawingList = []
  376. this.idGlobal = 100
  377. }).catch(() => {});
  378. },
  379. drawingItemCopy(item, list) {
  380. let clone = deepClone(item)
  381. clone = this.createIdAndKey(clone)
  382. list.push(clone)
  383. this.activeFormItem(clone)
  384. },
  385. drawingItemDelete(index, list) {
  386. list.splice(index, 1)
  387. this.$nextTick(() => {
  388. const len = this.drawingList.length
  389. if (len) {
  390. this.activeFormItem(this.drawingList[len - 1])
  391. }
  392. })
  393. },
  394. generateCode() {
  395. const { type } = this.generateConf
  396. this.AssembleFormData()
  397. const script = vueScript(makeUpJs(this.formData, type))
  398. const html = vueTemplate(makeUpHtml(this.formData, type))
  399. const css = cssStyle(makeUpCss(this.formData))
  400. return beautifier.html(html + script + css, beautifierConf.html)
  401. },
  402. showJson() {
  403. this.AssembleFormData()
  404. this.jsonDrawerVisible = true
  405. },
  406. download() {
  407. this.dialogVisible = true
  408. this.showFileName = true
  409. this.operationType = 'download'
  410. },
  411. run() {
  412. this.dialogVisible = true
  413. this.showFileName = false
  414. this.operationType = 'run'
  415. },
  416. copy() {
  417. this.dialogVisible = true
  418. this.showFileName = false
  419. this.operationType = 'copy'
  420. },
  421. tagChange(newTag) {
  422. newTag = this.cloneComponent(newTag)
  423. const config = newTag.__config__
  424. newTag.__vModel__ = this.activeData.__vModel__
  425. config.formId = this.activeId
  426. config.span = this.activeData.__config__.span
  427. this.activeData.__config__.tag = config.tag
  428. this.activeData.__config__.tagIcon = config.tagIcon
  429. this.activeData.__config__.document = config.document
  430. if (typeof this.activeData.__config__.defaultValue === typeof config.defaultValue) {
  431. config.defaultValue = this.activeData.__config__.defaultValue
  432. }
  433. Object.keys(newTag).forEach(key => {
  434. if (this.activeData[key] !== undefined) {
  435. newTag[key] = this.activeData[key]
  436. }
  437. })
  438. this.activeData = newTag
  439. this.updateDrawingList(newTag, this.drawingList)
  440. },
  441. updateDrawingList(newTag, list) {
  442. const index = list.findIndex(item => item.__config__.formId === this.activeId)
  443. if (index > -1) {
  444. list.splice(index, 1, newTag)
  445. } else {
  446. list.forEach(item => {
  447. if (Array.isArray(item.__config__.children)) this.updateDrawingList(newTag, item.__config__.children)
  448. })
  449. }
  450. },
  451. refreshJson(data) {
  452. this.drawingList = deepClone(data.fields)
  453. delete data.fields
  454. this.formConf = data
  455. }
  456. }
  457. }
  458. </script>
  459. <style lang='scss'>
  460. @import '@/styles/home';
  461. </style>