代码自动生成工具
概述
为什么会想着去写这个东西,主要还是因为懒在3家创业公司待过每次都是遍体鳞伤,工作很累。老板想2,3个人去实现别人公司几十人才能完成的软件工作。而且还要求你快,每天8小时肯定是完不成啊这就出现了自愿加班原则而且不给加班费。
有段时间我在思考一个问题:像这样的项目,我不能按时完成是我的技术问题还是公司问题还是其他的问题。那换种思路,假设让一个阿里的大牛自己一个人去搭建一个软件平台(比如一套B2B2C商城系统)1,2个月应该是搭不完的。那么多业务逻辑主要还是时间问题,技术上其实也不算特别复杂。
反思
1、初创团队没有技术沉淀(无可复用组件和规范化代码)
2、团队内部磨合差,技术栈不统一。能力也不统一
3、缺乏凝聚力和团队使命感
代码自动生成工具思路
1、常用代码块的封装
2、通过JSON配置文件自动生成代码
3、字符串模版
一、以表格为例子
开发管理后台,表格形式的列表出现的频率最高,我们先拿它下手。
我先安装一个小的依赖包。
npm install clipboard
然后写一个工具方法,clipboard.js
import Vue from 'vue'
import Clipboard from 'clipboard'
function clipboardSuccess() {
Vue.prototype.$message({
message: 'Copy successfully',
type: 'success',
duration: 1500
})
}
function clipboardError() {
Vue.prototype.$message({
message: 'Copy failed',
type: 'error'
})
}
export default function handleClipboard(text, event) {
const clipboard = new Clipboard(event.target, {
text: () => text
})
clipboard.on('success', () => {
clipboardSuccess()
clipboard.off('error')
clipboard.off('success')
clipboard.destroy()
})
clipboard.on('error', () => {
clipboardError()
clipboard.off('error')
clipboard.off('success')
clipboard.destroy()
})
clipboard.onClick(event)
}
调用方式
1、 <el-button @click='htmlCopy("", $event)'>获取表格html</el-button>
2、 import clip from './../../utils/clipboard'
3、htmlCopy(text, event) {
const tableData = this.tableData
const tableRow = this.tableDataObj
const tbaleHtml = temp.tableToHtml(tableData, tableRow)
clip(tbaleHtml, event)
this.test = tbaleHtml
}
把json串生成对应的表格并且通过ES6的新特性把它转换成对应的html
// 生成的json串数据
{"tableData":"music","rowData":[{"rowName":"ID","rowData":"id","rowWidth":"100"},{"rowName":"名称","rowData":"name","rowWidth":"200"},{"rowName":"状态","rowData":"status","rowWidth":"80"}]}
/**
* @param tableData 表格数据源
* @param tableRow 表格行信息
* @returns {string} 表格的html模版
*/
tableToHtml: (tableData, tableRow) => {
var tableRowData = tableRow
var rowStr = ``
// 表格列数据拼接
for (let i = 0; i < tableRow.rowData.length; i++) {
const tempData = `
<el-table-column
header-align="center"
prop="${tableRowData.rowData[i].rowData}"
label="${tableRowData.rowData[i].rowName}"
width="${tableRowData.rowData[i].rowWidth}">
</el-table-column>
`
rowStr += tempData
}
var templat = `
<el-table
ref="multipleTable"
:data="${tableData}"
stripe="true"
tooltip-effect="dark"
style="width: 100%;margin-top: 20px;text-align: center;border-radius: 5px;"
@selection-change="handleSelectionChange">
<el-table-column
header-align="center"
type="selection"
width="55">
</el-table-column>
${rowStr}
<el-table-column label="操作" header-align="center">
<template slot-scope="scope">
<el-button
size="mini"
type="danger"
@click="handleDelete(scope.$index, scope.row)">删除</el-button>
</template>
</el-table-column>
</el-table>
`
return templat
},
// 表格中需要的数据
tableToData: (tableData, tableRow) => {
var templat = ``
var rowStr = ``
for (let i = 0; i < tableRow.rowData.length; i++) {
const tempData = `${tableRow.rowData[i].rowData}: '',
`
rowStr += tempData
}
templat = `
${tableData}: '',
${rowStr}
`
return templat
}