26 changed files with 484 additions and 1884 deletions
@ -1,18 +0,0 @@ |
|||
const styles = { |
|||
'el-rate': '.el-rate{display: inline-block; vertical-align: text-top;}', |
|||
'el-upload': '.el-upload__tip{line-height: 1.2;}' |
|||
} |
|||
|
|||
function addCss(cssList, el) { |
|||
const css = styles[el.__config__.tag] |
|||
css && cssList.indexOf(css) === -1 && cssList.push(css) |
|||
if (el.__config__.children) { |
|||
el.__config__.children.forEach(el2 => addCss(cssList, el2)) |
|||
} |
|||
} |
|||
|
|||
export function makeUpCss(conf) { |
|||
const cssList = [] |
|||
conf.fields.forEach(el => addCss(cssList, el)) |
|||
return cssList.join('\n') |
|||
} |
|||
@ -1,399 +0,0 @@ |
|||
/* eslint-disable max-len */ |
|||
import ruleTrigger from './ruleTrigger' |
|||
|
|||
let confGlobal |
|||
let someSpanIsNot24 |
|||
|
|||
export function dialogWrapper(str) { |
|||
return `<el-dialog v-bind="$attrs" v-on="$listeners" @open="onOpen" @close="onClose" title="Dialog Titile">
|
|||
${str} |
|||
<div slot="footer"> |
|||
<el-button @click="close">取消</el-button> |
|||
<el-button type="primary" @click="handelConfirm">确定</el-button> |
|||
</div> |
|||
</el-dialog>` |
|||
} |
|||
|
|||
export function vueTemplate(str) { |
|||
return `<template>
|
|||
<div> |
|||
${str} |
|||
</div> |
|||
</template>` |
|||
} |
|||
|
|||
export function vueScript(str) { |
|||
return `<script>
|
|||
${str} |
|||
</script>` |
|||
} |
|||
|
|||
export function cssStyle(cssStr) { |
|||
return `<style>
|
|||
${cssStr} |
|||
</style>` |
|||
} |
|||
|
|||
function buildFormTemplate(scheme, child, type) { |
|||
let labelPosition = '' |
|||
if (scheme.labelPosition !== 'right') { |
|||
labelPosition = `label-position="${scheme.labelPosition}"` |
|||
} |
|||
const disabled = scheme.disabled ? `:disabled="${scheme.disabled}"` : '' |
|||
let str = `<el-form ref="${scheme.formRef}" :model="${scheme.formModel}" :rules="${scheme.formRules}" size="${scheme.size}" ${disabled} label-width="${scheme.labelWidth}px" ${labelPosition}>
|
|||
${child} |
|||
${buildFromBtns(scheme, type)} |
|||
</el-form>` |
|||
if (someSpanIsNot24) { |
|||
str = `<el-row :gutter="${scheme.gutter}">
|
|||
${str} |
|||
</el-row>` |
|||
} |
|||
return str |
|||
} |
|||
|
|||
function buildFromBtns(scheme, type) { |
|||
let str = '' |
|||
if (scheme.formBtns && type === 'file') { |
|||
str = `<el-form-item size="large">
|
|||
<el-button type="primary" @click="submitForm">提交</el-button> |
|||
<el-button @click="resetForm">重置</el-button> |
|||
</el-form-item>` |
|||
if (someSpanIsNot24) { |
|||
str = `<el-col :span="24">
|
|||
${str} |
|||
</el-col>` |
|||
} |
|||
} |
|||
return str |
|||
} |
|||
|
|||
// span不为24的用el-col包裹
|
|||
function colWrapper(scheme, str) { |
|||
if (someSpanIsNot24 || scheme.__config__.span !== 24) { |
|||
return `<el-col :span="${scheme.__config__.span}">
|
|||
${str} |
|||
</el-col>` |
|||
} |
|||
return str |
|||
} |
|||
|
|||
const layouts = { |
|||
colFormItem(scheme) { |
|||
const config = scheme.__config__ |
|||
let labelWidth = '' |
|||
let label = `label="${config.label}"` |
|||
if (config.labelWidth && config.labelWidth !== confGlobal.labelWidth) { |
|||
labelWidth = `label-width="${config.labelWidth}px"` |
|||
} |
|||
if (config.showLabel === false) { |
|||
labelWidth = 'label-width="0"' |
|||
label = '' |
|||
} |
|||
const required = !ruleTrigger[config.tag] && config.required ? 'required' : '' |
|||
const tagDom = tags[config.tag] ? tags[config.tag](scheme) : null |
|||
let str = `<el-form-item ${labelWidth} ${label} prop="${scheme.__vModel__}" ${required}>
|
|||
${tagDom} |
|||
</el-form-item>` |
|||
str = colWrapper(scheme, str) |
|||
return str |
|||
}, |
|||
rowFormItem(scheme) { |
|||
const config = scheme.__config__ |
|||
const type = scheme.type === 'default' ? '' : `type="${scheme.type}"` |
|||
const justify = scheme.type === 'default' ? '' : `justify="${scheme.justify}"` |
|||
const align = scheme.type === 'default' ? '' : `align="${scheme.align}"` |
|||
const gutter = scheme.gutter ? `:gutter="${scheme.gutter}"` : '' |
|||
const children = config.children.map(el => layouts[el.__config__.layout](el)) |
|||
let str = `<el-row ${type} ${justify} ${align} ${gutter}>
|
|||
${children.join('\n')} |
|||
</el-row>` |
|||
str = colWrapper(scheme, str) |
|||
return str |
|||
} |
|||
} |
|||
|
|||
const tags = { |
|||
'el-button': el => { |
|||
const { |
|||
tag, disabled |
|||
} = attrBuilder(el) |
|||
const type = el.type ? `type="${el.type}"` : '' |
|||
const icon = el.icon ? `icon="${el.icon}"` : '' |
|||
const round = el.round ? 'round' : '' |
|||
const size = el.size ? `size="${el.size}"` : '' |
|||
const plain = el.plain ? 'plain' : '' |
|||
const circle = el.circle ? 'circle' : '' |
|||
let child = buildElButtonChild(el) |
|||
|
|||
if (child) child = `\n${child}\n` // 换行
|
|||
return `<${tag} ${type} ${icon} ${round} ${size} ${plain} ${disabled} ${circle}>${child}</${tag}>` |
|||
}, |
|||
'el-input': el => { |
|||
const { |
|||
tag, disabled, vModel, clearable, placeholder, width |
|||
} = attrBuilder(el) |
|||
const maxlength = el.maxlength ? `:maxlength="${el.maxlength}"` : '' |
|||
const showWordLimit = el['show-word-limit'] ? 'show-word-limit' : '' |
|||
const readonly = el.readonly ? 'readonly' : '' |
|||
const prefixIcon = el['prefix-icon'] ? `prefix-icon='${el['prefix-icon']}'` : '' |
|||
const suffixIcon = el['suffix-icon'] ? `suffix-icon='${el['suffix-icon']}'` : '' |
|||
const showPassword = el['show-password'] ? 'show-password' : '' |
|||
const type = el.type ? `type="${el.type}"` : '' |
|||
const autosize = el.autosize && el.autosize.minRows |
|||
? `:autosize="{minRows: ${el.autosize.minRows}, maxRows: ${el.autosize.maxRows}}"` |
|||
: '' |
|||
let child = buildElInputChild(el) |
|||
|
|||
if (child) child = `\n${child}\n` // 换行
|
|||
return `<${tag} ${vModel} ${type} ${placeholder} ${maxlength} ${showWordLimit} ${readonly} ${disabled} ${clearable} ${prefixIcon} ${suffixIcon} ${showPassword} ${autosize} ${width}>${child}</${tag}>` |
|||
}, |
|||
'el-input-number': el => { |
|||
const { |
|||
tag, disabled, vModel, placeholder |
|||
} = attrBuilder(el) |
|||
const controlsPosition = el['controls-position'] ? `controls-position=${el['controls-position']}` : '' |
|||
const min = el.min ? `:min='${el.min}'` : '' |
|||
const max = el.max ? `:max='${el.max}'` : '' |
|||
const step = el.step ? `:step='${el.step}'` : '' |
|||
const stepStrictly = el['step-strictly'] ? 'step-strictly' : '' |
|||
const precision = el.precision ? `:precision='${el.precision}'` : '' |
|||
|
|||
return `<${tag} ${vModel} ${placeholder} ${step} ${stepStrictly} ${precision} ${controlsPosition} ${min} ${max} ${disabled}></${tag}>` |
|||
}, |
|||
'el-select': el => { |
|||
const { |
|||
tag, disabled, vModel, clearable, placeholder, width |
|||
} = attrBuilder(el) |
|||
const filterable = el.filterable ? 'filterable' : '' |
|||
const multiple = el.multiple ? 'multiple' : '' |
|||
let child = buildElSelectChild(el) |
|||
|
|||
if (child) child = `\n${child}\n` // 换行
|
|||
return `<${tag} ${vModel} ${placeholder} ${disabled} ${multiple} ${filterable} ${clearable} ${width}>${child}</${tag}>` |
|||
}, |
|||
'el-radio-group': el => { |
|||
const { tag, disabled, vModel } = attrBuilder(el) |
|||
const size = `size="${el.size}"` |
|||
let child = buildElRadioGroupChild(el) |
|||
|
|||
if (child) child = `\n${child}\n` // 换行
|
|||
return `<${tag} ${vModel} ${size} ${disabled}>${child}</${tag}>` |
|||
}, |
|||
'el-checkbox-group': el => { |
|||
const { tag, disabled, vModel } = attrBuilder(el) |
|||
const size = `size="${el.size}"` |
|||
const min = el.min ? `:min="${el.min}"` : '' |
|||
const max = el.max ? `:max="${el.max}"` : '' |
|||
let child = buildElCheckboxGroupChild(el) |
|||
|
|||
if (child) child = `\n${child}\n` // 换行
|
|||
return `<${tag} ${vModel} ${min} ${max} ${size} ${disabled}>${child}</${tag}>` |
|||
}, |
|||
'el-switch': el => { |
|||
const { tag, disabled, vModel } = attrBuilder(el) |
|||
const activeText = el['active-text'] ? `active-text="${el['active-text']}"` : '' |
|||
const inactiveText = el['inactive-text'] ? `inactive-text="${el['inactive-text']}"` : '' |
|||
const activeColor = el['active-color'] ? `active-color="${el['active-color']}"` : '' |
|||
const inactiveColor = el['inactive-color'] ? `inactive-color="${el['inactive-color']}"` : '' |
|||
const activeValue = el['active-value'] !== true ? `:active-value='${JSON.stringify(el['active-value'])}'` : '' |
|||
const inactiveValue = el['inactive-value'] !== false ? `:inactive-value='${JSON.stringify(el['inactive-value'])}'` : '' |
|||
|
|||
return `<${tag} ${vModel} ${activeText} ${inactiveText} ${activeColor} ${inactiveColor} ${activeValue} ${inactiveValue} ${disabled}></${tag}>` |
|||
}, |
|||
'el-cascader': el => { |
|||
const { |
|||
tag, disabled, vModel, clearable, placeholder, width |
|||
} = attrBuilder(el) |
|||
const options = el.options ? `:options="${el.__vModel__}Options"` : '' |
|||
const props = el.props ? `:props="${el.__vModel__}Props"` : '' |
|||
const showAllLevels = el['show-all-levels'] ? '' : ':show-all-levels="false"' |
|||
const filterable = el.filterable ? 'filterable' : '' |
|||
const separator = el.separator === '/' ? '' : `separator="${el.separator}"` |
|||
|
|||
return `<${tag} ${vModel} ${options} ${props} ${width} ${showAllLevels} ${placeholder} ${separator} ${filterable} ${clearable} ${disabled}></${tag}>` |
|||
}, |
|||
'el-slider': el => { |
|||
const { tag, disabled, vModel } = attrBuilder(el) |
|||
const min = el.min ? `:min='${el.min}'` : '' |
|||
const max = el.max ? `:max='${el.max}'` : '' |
|||
const step = el.step ? `:step='${el.step}'` : '' |
|||
const range = el.range ? 'range' : '' |
|||
const showStops = el['show-stops'] ? `:show-stops="${el['show-stops']}"` : '' |
|||
|
|||
return `<${tag} ${min} ${max} ${step} ${vModel} ${range} ${showStops} ${disabled}></${tag}>` |
|||
}, |
|||
'el-time-picker': el => { |
|||
const { |
|||
tag, disabled, vModel, clearable, placeholder, width |
|||
} = attrBuilder(el) |
|||
const startPlaceholder = el['start-placeholder'] ? `start-placeholder="${el['start-placeholder']}"` : '' |
|||
const endPlaceholder = el['end-placeholder'] ? `end-placeholder="${el['end-placeholder']}"` : '' |
|||
const rangeSeparator = el['range-separator'] ? `range-separator="${el['range-separator']}"` : '' |
|||
const isRange = el['is-range'] ? 'is-range' : '' |
|||
const format = el.format ? `format="${el.format}"` : '' |
|||
const valueFormat = el['value-format'] ? `value-format="${el['value-format']}"` : '' |
|||
const pickerOptions = el['picker-options'] ? `:picker-options='${JSON.stringify(el['picker-options'])}'` : '' |
|||
|
|||
return `<${tag} ${vModel} ${isRange} ${format} ${valueFormat} ${pickerOptions} ${width} ${placeholder} ${startPlaceholder} ${endPlaceholder} ${rangeSeparator} ${clearable} ${disabled}></${tag}>` |
|||
}, |
|||
'el-date-picker': el => { |
|||
const { |
|||
tag, disabled, vModel, clearable, placeholder, width |
|||
} = attrBuilder(el) |
|||
const startPlaceholder = el['start-placeholder'] ? `start-placeholder="${el['start-placeholder']}"` : '' |
|||
const endPlaceholder = el['end-placeholder'] ? `end-placeholder="${el['end-placeholder']}"` : '' |
|||
const rangeSeparator = el['range-separator'] ? `range-separator="${el['range-separator']}"` : '' |
|||
const format = el.format ? `format="${el.format}"` : '' |
|||
const valueFormat = el['value-format'] ? `value-format="${el['value-format']}"` : '' |
|||
const type = el.type === 'date' ? '' : `type="${el.type}"` |
|||
const readonly = el.readonly ? 'readonly' : '' |
|||
|
|||
return `<${tag} ${type} ${vModel} ${format} ${valueFormat} ${width} ${placeholder} ${startPlaceholder} ${endPlaceholder} ${rangeSeparator} ${clearable} ${readonly} ${disabled}></${tag}>` |
|||
}, |
|||
'el-rate': el => { |
|||
const { tag, disabled, vModel } = attrBuilder(el) |
|||
const max = el.max ? `:max='${el.max}'` : '' |
|||
const allowHalf = el['allow-half'] ? 'allow-half' : '' |
|||
const showText = el['show-text'] ? 'show-text' : '' |
|||
const showScore = el['show-score'] ? 'show-score' : '' |
|||
|
|||
return `<${tag} ${vModel} ${max} ${allowHalf} ${showText} ${showScore} ${disabled}></${tag}>` |
|||
}, |
|||
'el-color-picker': el => { |
|||
const { tag, disabled, vModel } = attrBuilder(el) |
|||
const size = `size="${el.size}"` |
|||
const showAlpha = el['show-alpha'] ? 'show-alpha' : '' |
|||
const colorFormat = el['color-format'] ? `color-format="${el['color-format']}"` : '' |
|||
|
|||
return `<${tag} ${vModel} ${size} ${showAlpha} ${colorFormat} ${disabled}></${tag}>` |
|||
}, |
|||
'el-upload': el => { |
|||
const { tag } = el.__config__ |
|||
const disabled = el.disabled ? ':disabled=\'true\'' : '' |
|||
const action = el.action ? `:action="${el.__vModel__}Action"` : '' |
|||
const multiple = el.multiple ? 'multiple' : '' |
|||
const listType = el['list-type'] !== 'text' ? `list-type="${el['list-type']}"` : '' |
|||
const accept = el.accept ? `accept="${el.accept}"` : '' |
|||
const name = el.name !== 'file' ? `name="${el.name}"` : '' |
|||
const autoUpload = el['auto-upload'] === false ? ':auto-upload="false"' : '' |
|||
const beforeUpload = `:before-upload="${el.__vModel__}BeforeUpload"` |
|||
const fileList = `:file-list="${el.__vModel__}fileList"` |
|||
const ref = `ref="${el.__vModel__}"` |
|||
let child = buildElUploadChild(el) |
|||
|
|||
if (child) child = `\n${child}\n` // 换行
|
|||
return `<${tag} ${ref} ${fileList} ${action} ${autoUpload} ${multiple} ${beforeUpload} ${listType} ${accept} ${name} ${disabled}>${child}</${tag}>` |
|||
}, |
|||
tinymce: el => { |
|||
const { tag, vModel, placeholder } = attrBuilder(el) |
|||
const height = el.height ? `:height="${el.height}"` : '' |
|||
const branding = el.branding ? `:branding="${el.branding}"` : '' |
|||
return `<${tag} ${vModel} ${placeholder} ${height} ${branding}></${tag}>` |
|||
} |
|||
} |
|||
|
|||
function attrBuilder(el) { |
|||
return { |
|||
tag: el.__config__.tag, |
|||
vModel: `v-model="${confGlobal.formModel}.${el.__vModel__}"`, |
|||
clearable: el.clearable ? 'clearable' : '', |
|||
placeholder: el.placeholder ? `placeholder="${el.placeholder}"` : '', |
|||
width: el.style && el.style.width ? ':style="{width: \'100%\'}"' : '', |
|||
disabled: el.disabled ? ':disabled=\'true\'' : '' |
|||
} |
|||
} |
|||
|
|||
// el-buttin 子级
|
|||
function buildElButtonChild(scheme) { |
|||
const children = [] |
|||
const slot = scheme.__slot__ || {} |
|||
if (slot.default) { |
|||
children.push(slot.default) |
|||
} |
|||
return children.join('\n') |
|||
} |
|||
|
|||
// el-input 子级
|
|||
function buildElInputChild(scheme) { |
|||
const children = [] |
|||
const slot = scheme.__slot__ |
|||
if (slot && slot.prepend) { |
|||
children.push(`<template slot="prepend">${slot.prepend}</template>`) |
|||
} |
|||
if (slot && slot.append) { |
|||
children.push(`<template slot="append">${slot.append}</template>`) |
|||
} |
|||
return children.join('\n') |
|||
} |
|||
|
|||
// el-select 子级
|
|||
function buildElSelectChild(scheme) { |
|||
const children = [] |
|||
const slot = scheme.__slot__ |
|||
if (slot && slot.options && slot.options.length) { |
|||
children.push(`<el-option v-for="(item, index) in ${scheme.__vModel__}Options" :key="index" :label="item.label" :value="item.value" :disabled="item.disabled"></el-option>`) |
|||
} |
|||
return children.join('\n') |
|||
} |
|||
|
|||
// el-radio-group 子级
|
|||
function buildElRadioGroupChild(scheme) { |
|||
const children = [] |
|||
const slot = scheme.__slot__ |
|||
const config = scheme.__config__ |
|||
if (slot && slot.options && slot.options.length) { |
|||
const tag = config.optionType === 'button' ? 'el-radio-button' : 'el-radio' |
|||
const border = config.border ? 'border' : '' |
|||
children.push(`<${tag} v-for="(item, index) in ${scheme.__vModel__}Options" :key="index" :label="item.value" :disabled="item.disabled" ${border}>{{item.label}}</${tag}>`) |
|||
} |
|||
return children.join('\n') |
|||
} |
|||
|
|||
// el-checkbox-group 子级
|
|||
function buildElCheckboxGroupChild(scheme) { |
|||
const children = [] |
|||
const slot = scheme.__slot__ |
|||
const config = scheme.__config__ |
|||
if (slot && slot.options && slot.options.length) { |
|||
const tag = config.optionType === 'button' ? 'el-checkbox-button' : 'el-checkbox' |
|||
const border = config.border ? 'border' : '' |
|||
children.push(`<${tag} v-for="(item, index) in ${scheme.__vModel__}Options" :key="index" :label="item.value" :disabled="item.disabled" ${border}>{{item.label}}</${tag}>`) |
|||
} |
|||
return children.join('\n') |
|||
} |
|||
|
|||
// el-upload 子级
|
|||
function buildElUploadChild(scheme) { |
|||
const list = [] |
|||
const config = scheme.__config__ |
|||
if (scheme['list-type'] === 'picture-card') list.push('<i class="el-icon-plus"></i>') |
|||
else list.push(`<el-button size="small" type="primary" icon="el-icon-upload">${config.buttonText}</el-button>`) |
|||
if (config.showTip) list.push(`<div slot="tip" class="el-upload__tip">只能上传不超过 ${config.fileSize}${config.sizeUnit} 的${scheme.accept}文件</div>`) |
|||
return list.join('\n') |
|||
} |
|||
|
|||
/** |
|||
* 组装html代码。【入口函数】 |
|||
* @param {Object} formConfig 整个表单配置 |
|||
* @param {String} type 生成类型,文件或弹窗等 |
|||
*/ |
|||
export function makeUpHtml(formConfig, type) { |
|||
const htmlList = [] |
|||
confGlobal = formConfig |
|||
// 判断布局是否都沾满了24个栅格,以备后续简化代码结构
|
|||
someSpanIsNot24 = formConfig.fields.some(item => item.__config__.span !== 24) |
|||
// 遍历渲染每个组件成html
|
|||
formConfig.fields.forEach(el => { |
|||
htmlList.push(layouts[el.__config__.layout](el)) |
|||
}) |
|||
const htmlStr = htmlList.join('\n') |
|||
// 将组件代码放进form标签
|
|||
let temp = buildFormTemplate(formConfig, htmlStr, type) |
|||
// dialog标签包裹代码
|
|||
if (type === 'dialog') { |
|||
temp = dialogWrapper(temp) |
|||
} |
|||
confGlobal = null |
|||
return temp |
|||
} |
|||
@ -1,271 +0,0 @@ |
|||
import { isArray } from 'util' |
|||
import { exportDefault, titleCase, deepClone } from '@/utils/index' |
|||
import ruleTrigger from './ruleTrigger' |
|||
|
|||
const units = { |
|||
KB: '1024', |
|||
MB: '1024 / 1024', |
|||
GB: '1024 / 1024 / 1024' |
|||
} |
|||
let confGlobal |
|||
const inheritAttrs = { |
|||
file: '', |
|||
dialog: 'inheritAttrs: false,' |
|||
} |
|||
|
|||
/** |
|||
* 组装js 【入口函数】 |
|||
* @param {Object} formConfig 整个表单配置 |
|||
* @param {String} type 生成类型,文件或弹窗等 |
|||
*/ |
|||
export function makeUpJs(formConfig, type) { |
|||
confGlobal = formConfig = deepClone(formConfig) |
|||
const dataList = [] |
|||
const ruleList = [] |
|||
const optionsList = [] |
|||
const propsList = [] |
|||
const methodList = mixinMethod(type) |
|||
const uploadVarList = [] |
|||
const created = [] |
|||
|
|||
formConfig.fields.forEach(el => { |
|||
buildAttributes(el, dataList, ruleList, optionsList, methodList, propsList, uploadVarList, created) |
|||
}) |
|||
|
|||
const script = buildexport( |
|||
formConfig, |
|||
type, |
|||
dataList.join('\n'), |
|||
ruleList.join('\n'), |
|||
optionsList.join('\n'), |
|||
uploadVarList.join('\n'), |
|||
propsList.join('\n'), |
|||
methodList.join('\n'), |
|||
created.join('\n') |
|||
) |
|||
confGlobal = null |
|||
return script |
|||
} |
|||
|
|||
// 构建组件属性
|
|||
function buildAttributes(scheme, dataList, ruleList, optionsList, methodList, propsList, uploadVarList, created) { |
|||
const config = scheme.__config__ |
|||
const slot = scheme.__slot__ |
|||
buildData(scheme, dataList) |
|||
buildRules(scheme, ruleList) |
|||
|
|||
// 特殊处理options属性
|
|||
if (scheme.options || (slot && slot.options && slot.options.length)) { |
|||
buildOptions(scheme, optionsList) |
|||
if (config.dataType === 'dynamic') { |
|||
const model = `${scheme.__vModel__}Options` |
|||
const options = titleCase(model) |
|||
const methodName = `get${options}` |
|||
buildOptionMethod(methodName, model, methodList, scheme) |
|||
callInCreated(methodName, created) |
|||
} |
|||
} |
|||
|
|||
// 处理props
|
|||
if (scheme.props && scheme.props.props) { |
|||
buildProps(scheme, propsList) |
|||
} |
|||
|
|||
// 处理el-upload的action
|
|||
if (scheme.action && config.tag === 'el-upload') { |
|||
uploadVarList.push( |
|||
`${scheme.__vModel__}Action: '${scheme.action}',
|
|||
${scheme.__vModel__}fileList: [],` |
|||
) |
|||
methodList.push(buildBeforeUpload(scheme)) |
|||
// 非自动上传时,生成手动上传的函数
|
|||
if (!scheme['auto-upload']) { |
|||
methodList.push(buildSubmitUpload(scheme)) |
|||
} |
|||
} |
|||
|
|||
// 构建子级组件属性
|
|||
if (config.children) { |
|||
config.children.forEach(item => { |
|||
buildAttributes(item, dataList, ruleList, optionsList, methodList, propsList, uploadVarList, created) |
|||
}) |
|||
} |
|||
} |
|||
|
|||
// 在Created调用函数
|
|||
function callInCreated(methodName, created) { |
|||
created.push(`this.${methodName}()`) |
|||
} |
|||
|
|||
// 混入处理函数
|
|||
function mixinMethod(type) { |
|||
const list = []; const |
|||
minxins = { |
|||
file: confGlobal.formBtns ? { |
|||
submitForm: `submitForm() {
|
|||
this.$refs['${confGlobal.formRef}'].validate(valid => { |
|||
if(!valid) return |
|||
// TODO 提交表单
|
|||
}) |
|||
},`,
|
|||
resetForm: `resetForm() {
|
|||
this.$refs['${confGlobal.formRef}'].resetFields() |
|||
},` |
|||
} : null, |
|||
dialog: { |
|||
onOpen: 'onOpen() {},', |
|||
onClose: `onClose() {
|
|||
this.$refs['${confGlobal.formRef}'].resetFields() |
|||
},`,
|
|||
close: `close() {
|
|||
this.$emit('update:visible', false) |
|||
},`,
|
|||
handelConfirm: `handelConfirm() {
|
|||
this.$refs['${confGlobal.formRef}'].validate(valid => { |
|||
if(!valid) return |
|||
this.close() |
|||
}) |
|||
},` |
|||
} |
|||
} |
|||
|
|||
const methods = minxins[type] |
|||
if (methods) { |
|||
Object.keys(methods).forEach(key => { |
|||
list.push(methods[key]) |
|||
}) |
|||
} |
|||
|
|||
return list |
|||
} |
|||
|
|||
// 构建data
|
|||
function buildData(scheme, dataList) { |
|||
const config = scheme.__config__ |
|||
if (scheme.__vModel__ === undefined) return |
|||
const defaultValue = JSON.stringify(config.defaultValue) |
|||
dataList.push(`${scheme.__vModel__}: ${defaultValue},`) |
|||
} |
|||
|
|||
// 构建校验规则
|
|||
function buildRules(scheme, ruleList) { |
|||
const config = scheme.__config__ |
|||
if (scheme.__vModel__ === undefined) return |
|||
const rules = [] |
|||
if (ruleTrigger[config.tag]) { |
|||
if (config.required) { |
|||
const type = isArray(config.defaultValue) ? 'type: \'array\',' : '' |
|||
let message = isArray(config.defaultValue) ? `请至少选择一个${config.label}` : scheme.placeholder |
|||
if (message === undefined) message = `${config.label}不能为空` |
|||
rules.push(`{ required: true, ${type} message: '${message}', trigger: '${ruleTrigger[config.tag]}' }`) |
|||
} |
|||
if (config.regList && isArray(config.regList)) { |
|||
config.regList.forEach(item => { |
|||
if (item.pattern) { |
|||
rules.push( |
|||
`{ pattern: ${eval(item.pattern)}, message: '${item.message}', trigger: '${ruleTrigger[config.tag]}' }` |
|||
) |
|||
} |
|||
}) |
|||
} |
|||
ruleList.push(`${scheme.__vModel__}: [${rules.join(',')}],`) |
|||
} |
|||
} |
|||
|
|||
// 构建options
|
|||
function buildOptions(scheme, optionsList) { |
|||
if (scheme.__vModel__ === undefined) return |
|||
// el-cascader直接有options属性,其他组件都是定义在slot中,所以有两处判断
|
|||
let { options } = scheme |
|||
if (!options) options = scheme.__slot__.options |
|||
if (scheme.__config__.dataType === 'dynamic') { options = [] } |
|||
const str = `${scheme.__vModel__}Options: ${JSON.stringify(options)},` |
|||
optionsList.push(str) |
|||
} |
|||
|
|||
function buildProps(scheme, propsList) { |
|||
const str = `${scheme.__vModel__}Props: ${JSON.stringify(scheme.props.props)},` |
|||
propsList.push(str) |
|||
} |
|||
|
|||
// el-upload的BeforeUpload
|
|||
function buildBeforeUpload(scheme) { |
|||
const config = scheme.__config__ |
|||
const unitNum = units[config.sizeUnit]; let rightSizeCode = ''; let acceptCode = ''; const |
|||
returnList = [] |
|||
if (config.fileSize) { |
|||
rightSizeCode = `let isRightSize = file.size / ${unitNum} < ${config.fileSize} |
|||
if(!isRightSize){ |
|||
this.$message.error('文件大小超过 ${config.fileSize}${config.sizeUnit}') |
|||
}` |
|||
returnList.push('isRightSize') |
|||
} |
|||
if (scheme.accept) { |
|||
acceptCode = `let isAccept = new RegExp('${scheme.accept}').test(file.type)
|
|||
if(!isAccept){ |
|||
this.$message.error('应该选择${scheme.accept}类型的文件') |
|||
}` |
|||
returnList.push('isAccept') |
|||
} |
|||
const str = `${scheme.__vModel__}BeforeUpload(file) {
|
|||
${rightSizeCode} |
|||
${acceptCode} |
|||
return ${returnList.join('&&')} |
|||
},` |
|||
return returnList.length ? str : '' |
|||
} |
|||
|
|||
// el-upload的submit
|
|||
function buildSubmitUpload(scheme) { |
|||
const str = `submitUpload() {
|
|||
this.$refs['${scheme.__vModel__}'].submit() |
|||
},` |
|||
return str |
|||
} |
|||
|
|||
function buildOptionMethod(methodName, model, methodList, scheme) { |
|||
const config = scheme.__config__ |
|||
const str = `${methodName}() {
|
|||
// 注意:this.$axios是通过Vue.prototype.$axios = axios挂载产生的
|
|||
this.$axios({ |
|||
method: '${config.method}', |
|||
url: '${config.url}' |
|||
}).then(resp => { |
|||
var { data } = resp |
|||
this.${model} = data.${config.dataKey} |
|||
}) |
|||
},` |
|||
methodList.push(str) |
|||
} |
|||
|
|||
// js整体拼接
|
|||
function buildexport(conf, type, data, rules, selectOptions, uploadVar, props, methods, created) { |
|||
const str = `${exportDefault}{
|
|||
${inheritAttrs[type]} |
|||
components: {}, |
|||
props: [], |
|||
data () { |
|||
return { |
|||
${conf.formModel}: { |
|||
${data} |
|||
}, |
|||
${conf.formRules}: { |
|||
${rules} |
|||
}, |
|||
${uploadVar} |
|||
${selectOptions} |
|||
${props} |
|||
} |
|||
}, |
|||
computed: {}, |
|||
watch: {}, |
|||
created () { |
|||
${created} |
|||
}, |
|||
mounted () {}, |
|||
methods: { |
|||
${methods} |
|||
} |
|||
}` |
|||
return str |
|||
} |
|||
@ -1,26 +0,0 @@ |
|||
import loadScript from './loadScript' |
|||
import ELEMENT from 'element-ui' |
|||
|
|||
let beautifierObj |
|||
|
|||
export default function loadBeautifier(cb) { |
|||
if (beautifierObj) { |
|||
cb(beautifierObj) |
|||
return |
|||
} |
|||
|
|||
const loading = ELEMENT.Loading.service({ |
|||
fullscreen: true, |
|||
lock: true, |
|||
text: '格式化资源加载中...', |
|||
spinner: 'el-icon-loading', |
|||
background: 'rgba(255, 255, 255, 0.5)' |
|||
}) |
|||
|
|||
loadScript('https://lib.baomitu.com/js-beautify/1.10.2/beautifier.min.js', () => { |
|||
loading.close() |
|||
// eslint-disable-next-line no-undef
|
|||
beautifierObj = beautifier |
|||
cb(beautifierObj) |
|||
}) |
|||
} |
|||
@ -1,42 +0,0 @@ |
|||
import { loadScriptQueue } from './loadScript' |
|||
import ELEMENT from 'element-ui' |
|||
|
|||
// monaco-editor单例
|
|||
let monacoEidtor |
|||
|
|||
/** |
|||
* 动态加载monaco-editor cdn资源 |
|||
* @param {Function} cb 回调,必填 |
|||
*/ |
|||
export default function loadMonaco(cb) { |
|||
if (monacoEidtor) { |
|||
cb(monacoEidtor) |
|||
return |
|||
} |
|||
|
|||
const vs = 'https://lib.baomitu.com/monaco-editor/0.19.3/min/vs' |
|||
|
|||
// 使用element ui实现加载提示
|
|||
const loading = ELEMENT.Loading.service({ |
|||
fullscreen: true, |
|||
lock: true, |
|||
text: '编辑器资源初始化中...', |
|||
spinner: 'el-icon-loading', |
|||
background: 'rgba(255, 255, 255, 0.5)' |
|||
}) |
|||
|
|||
!window.require && (window.require = {}) |
|||
!window.require.paths && (window.require.paths = {}) |
|||
window.require.paths.vs = vs |
|||
|
|||
loadScriptQueue([ |
|||
`${vs}/loader.js`, |
|||
`${vs}/editor/editor.main.nls.js`, |
|||
`${vs}/editor/editor.main.js` |
|||
], () => { |
|||
loading.close() |
|||
// eslint-disable-next-line no-undef
|
|||
monacoEidtor = monaco |
|||
cb(monacoEidtor) |
|||
}) |
|||
} |
|||
@ -1,110 +0,0 @@ |
|||
<template> |
|||
<div> |
|||
<el-dialog |
|||
v-bind="$attrs" |
|||
width="500px" |
|||
:close-on-click-modal="false" |
|||
:modal-append-to-body="false" |
|||
v-on="$listeners" |
|||
@open="onOpen" |
|||
@close="onClose" |
|||
> |
|||
<el-row :gutter="15"> |
|||
<el-form |
|||
ref="elForm" |
|||
:model="formData" |
|||
:rules="rules" |
|||
size="medium" |
|||
label-width="100px" |
|||
> |
|||
<el-col :span="24"> |
|||
<el-form-item label="生成类型" prop="type"> |
|||
<el-radio-group v-model="formData.type"> |
|||
<el-radio-button |
|||
v-for="(item, index) in typeOptions" |
|||
:key="index" |
|||
:label="item.value" |
|||
:disabled="item.disabled" |
|||
> |
|||
{{ item.label }} |
|||
</el-radio-button> |
|||
</el-radio-group> |
|||
</el-form-item> |
|||
<el-form-item v-if="showFileName" label="文件名" prop="fileName"> |
|||
<el-input v-model="formData.fileName" placeholder="请输入文件名" clearable /> |
|||
</el-form-item> |
|||
</el-col> |
|||
</el-form> |
|||
</el-row> |
|||
|
|||
<div slot="footer"> |
|||
<el-button @click="close"> |
|||
取消 |
|||
</el-button> |
|||
<el-button type="primary" @click="handelConfirm"> |
|||
确定 |
|||
</el-button> |
|||
</div> |
|||
</el-dialog> |
|||
</div> |
|||
</template> |
|||
<script> |
|||
export default { |
|||
inheritAttrs: false, |
|||
props: ['showFileName'], |
|||
data() { |
|||
return { |
|||
formData: { |
|||
fileName: undefined, |
|||
type: 'file' |
|||
}, |
|||
rules: { |
|||
fileName: [{ |
|||
required: true, |
|||
message: '请输入文件名', |
|||
trigger: 'blur' |
|||
}], |
|||
type: [{ |
|||
required: true, |
|||
message: '生成类型不能为空', |
|||
trigger: 'change' |
|||
}] |
|||
}, |
|||
typeOptions: [{ |
|||
label: '页面', |
|||
value: 'file' |
|||
}, { |
|||
label: '弹窗', |
|||
value: 'dialog' |
|||
}] |
|||
} |
|||
}, |
|||
computed: { |
|||
}, |
|||
watch: {}, |
|||
mounted() {}, |
|||
methods: { |
|||
onOpen() { |
|||
if (this.showFileName) { |
|||
this.formData.fileName = `${+new Date()}.vue` |
|||
} |
|||
}, |
|||
onClose() { |
|||
}, |
|||
close(e) { |
|||
this.$emit('update:visible', false) |
|||
}, |
|||
handelConfirm() { |
|||
this.$refs.elForm.validate(valid => { |
|||
if (!valid) return |
|||
this.$emit('confirm', { ...this.formData }) |
|||
this.close() |
|||
}) |
|||
} |
|||
} |
|||
} |
|||
</script> |
|||
|
|||
<style lang="scss" scoped> |
|||
|
|||
</style> |
|||
@ -1,332 +0,0 @@ |
|||
<template> |
|||
<div> |
|||
<el-drawer v-bind="$attrs" v-on="$listeners" @opened="onOpen" @close="onClose"> |
|||
<div style="height:100%"> |
|||
<el-row style="height:100%;overflow:auto"> |
|||
<el-col :md="24" :lg="12" class="left-editor"> |
|||
<div class="setting" title="资源引用" @click="showResource"> |
|||
<el-badge :is-dot="!!resources.length" class="item"> |
|||
<i class="el-icon-setting" /> |
|||
</el-badge> |
|||
</div> |
|||
<el-tabs v-model="activeTab" type="card" class="editor-tabs"> |
|||
<el-tab-pane name="html"> |
|||
<span slot="label"> |
|||
<i v-if="activeTab==='html'" class="el-icon-edit" /> |
|||
<i v-else class="el-icon-document" /> |
|||
template |
|||
</span> |
|||
</el-tab-pane> |
|||
<el-tab-pane name="js"> |
|||
<span slot="label"> |
|||
<i v-if="activeTab==='js'" class="el-icon-edit" /> |
|||
<i v-else class="el-icon-document" /> |
|||
script |
|||
</span> |
|||
</el-tab-pane> |
|||
<el-tab-pane name="css"> |
|||
<span slot="label"> |
|||
<i v-if="activeTab==='css'" class="el-icon-edit" /> |
|||
<i v-else class="el-icon-document" /> |
|||
css |
|||
</span> |
|||
</el-tab-pane> |
|||
</el-tabs> |
|||
<div v-show="activeTab==='html'" id="editorHtml" class="tab-editor" /> |
|||
<div v-show="activeTab==='js'" id="editorJs" class="tab-editor" /> |
|||
<div v-show="activeTab==='css'" id="editorCss" class="tab-editor" /> |
|||
</el-col> |
|||
<el-col :md="24" :lg="12" class="right-preview"> |
|||
<div class="action-bar" :style="{'text-align': 'left'}"> |
|||
<span class="bar-btn" @click="runCode"> |
|||
<i class="el-icon-refresh" /> |
|||
刷新 |
|||
</span> |
|||
<span class="bar-btn" @click="exportFile"> |
|||
<i class="el-icon-download" /> |
|||
导出vue文件 |
|||
</span> |
|||
<span ref="copyBtn" class="bar-btn copy-btn"> |
|||
<i class="el-icon-document-copy" /> |
|||
复制代码 |
|||
</span> |
|||
<span class="bar-btn delete-btn" @click="$emit('update:visible', false)"> |
|||
<i class="el-icon-circle-close" /> |
|||
关闭 |
|||
</span> |
|||
</div> |
|||
<iframe |
|||
v-show="isIframeLoaded" |
|||
ref="previewPage" |
|||
class="result-wrapper" |
|||
frameborder="0" |
|||
src="preview.html" |
|||
@load="iframeLoad" |
|||
/> |
|||
<div v-show="!isIframeLoaded" v-loading="true" class="result-wrapper" /> |
|||
</el-col> |
|||
</el-row> |
|||
</div> |
|||
</el-drawer> |
|||
<resource-dialog |
|||
:visible.sync="resourceVisible" |
|||
:origin-resource="resources" |
|||
@save="setResource" |
|||
/> |
|||
</div> |
|||
</template> |
|||
<script> |
|||
import { parse } from '@babel/parser' |
|||
import ClipboardJS from 'clipboard' |
|||
import { saveAs } from 'file-saver' |
|||
import { |
|||
makeUpHtml, vueTemplate, vueScript, cssStyle |
|||
} from '@/components/generator/html' |
|||
import { makeUpJs } from '@/components/generator/js' |
|||
import { makeUpCss } from '@/components/generator/css' |
|||
import { exportDefault, beautifierConf, titleCase } from '@/utils/index' |
|||
import ResourceDialog from './ResourceDialog' |
|||
import loadMonaco from '@/utils/loadMonaco' |
|||
import loadBeautifier from '@/utils/loadBeautifier' |
|||
|
|||
const editorObj = { |
|||
html: null, |
|||
js: null, |
|||
css: null |
|||
} |
|||
const mode = { |
|||
html: 'html', |
|||
js: 'javascript', |
|||
css: 'css' |
|||
} |
|||
let beautifier |
|||
let monaco |
|||
|
|||
export default { |
|||
components: { ResourceDialog }, |
|||
props: ['formData', 'generateConf'], |
|||
data() { |
|||
return { |
|||
activeTab: 'html', |
|||
htmlCode: '', |
|||
jsCode: '', |
|||
cssCode: '', |
|||
codeFrame: '', |
|||
isIframeLoaded: false, |
|||
isInitcode: false, // 保证open后两个异步只执行一次runcode |
|||
isRefreshCode: false, // 每次打开都需要重新刷新代码 |
|||
resourceVisible: false, |
|||
scripts: [], |
|||
links: [], |
|||
monaco: null |
|||
} |
|||
}, |
|||
computed: { |
|||
resources() { |
|||
return this.scripts.concat(this.links) |
|||
} |
|||
}, |
|||
watch: {}, |
|||
created() { |
|||
}, |
|||
mounted() { |
|||
window.addEventListener('keydown', this.preventDefaultSave) |
|||
const clipboard = new ClipboardJS('.copy-btn', { |
|||
text: trigger => { |
|||
const codeStr = this.generateCode() |
|||
this.$notify({ |
|||
title: '成功', |
|||
message: '代码已复制到剪切板,可粘贴。', |
|||
type: 'success' |
|||
}) |
|||
return codeStr |
|||
} |
|||
}) |
|||
clipboard.on('error', e => { |
|||
this.$message.error('代码复制失败') |
|||
}) |
|||
}, |
|||
beforeDestroy() { |
|||
window.removeEventListener('keydown', this.preventDefaultSave) |
|||
}, |
|||
methods: { |
|||
preventDefaultSave(e) { |
|||
if (e.key === 's' && (e.metaKey || e.ctrlKey)) { |
|||
e.preventDefault() |
|||
} |
|||
}, |
|||
onOpen() { |
|||
const { type } = this.generateConf |
|||
this.htmlCode = makeUpHtml(this.formData, type) |
|||
this.jsCode = makeUpJs(this.formData, type) |
|||
this.cssCode = makeUpCss(this.formData) |
|||
|
|||
loadBeautifier(btf => { |
|||
beautifier = btf |
|||
this.htmlCode = beautifier.html(this.htmlCode, beautifierConf.html) |
|||
this.jsCode = beautifier.js(this.jsCode, beautifierConf.js) |
|||
this.cssCode = beautifier.css(this.cssCode, beautifierConf.html) |
|||
|
|||
loadMonaco(val => { |
|||
monaco = val |
|||
this.setEditorValue('editorHtml', 'html', this.htmlCode) |
|||
this.setEditorValue('editorJs', 'js', this.jsCode) |
|||
this.setEditorValue('editorCss', 'css', this.cssCode) |
|||
if (!this.isInitcode) { |
|||
this.isRefreshCode = true |
|||
this.isIframeLoaded && (this.isInitcode = true) && this.runCode() |
|||
} |
|||
}) |
|||
}) |
|||
}, |
|||
onClose() { |
|||
this.isInitcode = false |
|||
this.isRefreshCode = false |
|||
}, |
|||
iframeLoad() { |
|||
if (!this.isInitcode) { |
|||
this.isIframeLoaded = true |
|||
this.isRefreshCode && (this.isInitcode = true) && this.runCode() |
|||
} |
|||
}, |
|||
setEditorValue(id, type, codeStr) { |
|||
if (editorObj[type]) { |
|||
editorObj[type].setValue(codeStr) |
|||
} else { |
|||
editorObj[type] = monaco.editor.create(document.getElementById(id), { |
|||
value: codeStr, |
|||
theme: 'vs-dark', |
|||
language: mode[type], |
|||
automaticLayout: true |
|||
}) |
|||
} |
|||
// ctrl + s 刷新 |
|||
editorObj[type].onKeyDown(e => { |
|||
if (e.keyCode === 49 && (e.metaKey || e.ctrlKey)) { |
|||
this.runCode() |
|||
} |
|||
}) |
|||
}, |
|||
runCode() { |
|||
const jsCodeStr = editorObj.js.getValue() |
|||
try { |
|||
const ast = parse(jsCodeStr, { sourceType: 'module' }) |
|||
const astBody = ast.program.body |
|||
if (astBody.length > 1) { |
|||
this.$confirm( |
|||
'js格式不能识别,仅支持修改export default的对象内容', |
|||
'提示', |
|||
{ |
|||
type: 'warning' |
|||
} |
|||
) |
|||
return |
|||
} |
|||
if (astBody[0].type === 'ExportDefaultDeclaration') { |
|||
const postData = { |
|||
type: 'refreshFrame', |
|||
data: { |
|||
generateConf: this.generateConf, |
|||
html: editorObj.html.getValue(), |
|||
js: jsCodeStr.replace(exportDefault, ''), |
|||
css: editorObj.css.getValue(), |
|||
scripts: this.scripts, |
|||
links: this.links |
|||
} |
|||
} |
|||
|
|||
this.$refs.previewPage.contentWindow.postMessage( |
|||
postData, |
|||
location.origin |
|||
) |
|||
} else { |
|||
this.$message.error('请使用export default') |
|||
} |
|||
} catch (err) { |
|||
this.$message.error(`js错误:${err}`) |
|||
console.error(err) |
|||
} |
|||
}, |
|||
generateCode() { |
|||
const html = vueTemplate(editorObj.html.getValue()) |
|||
const script = vueScript(editorObj.js.getValue()) |
|||
const css = cssStyle(editorObj.css.getValue()) |
|||
return beautifier.html(html + script + css, beautifierConf.html) |
|||
}, |
|||
exportFile() { |
|||
this.$prompt('文件名:', '导出文件', { |
|||
inputValue: `${+new Date()}.vue`, |
|||
closeOnClickModal: false, |
|||
inputPlaceholder: '请输入文件名' |
|||
}).then(({ value }) => { |
|||
if (!value) value = `${+new Date()}.vue` |
|||
const codeStr = this.generateCode() |
|||
const blob = new Blob([codeStr], { type: 'text/plain;charset=utf-8' }) |
|||
saveAs(blob, value) |
|||
}) |
|||
}, |
|||
showResource() { |
|||
this.resourceVisible = true |
|||
}, |
|||
setResource(arr) { |
|||
const scripts = []; const |
|||
links = [] |
|||
if (Array.isArray(arr)) { |
|||
arr.forEach(item => { |
|||
if (item.endsWith('.css')) { |
|||
links.push(item) |
|||
} else { |
|||
scripts.push(item) |
|||
} |
|||
}) |
|||
this.scripts = scripts |
|||
this.links = links |
|||
} else { |
|||
this.scripts = [] |
|||
this.links = [] |
|||
} |
|||
} |
|||
} |
|||
} |
|||
</script> |
|||
|
|||
<style lang="scss" scoped> |
|||
@import '@/assets/styles/mixin.scss'; |
|||
.tab-editor { |
|||
position: absolute; |
|||
top: 33px; |
|||
bottom: 0; |
|||
left: 0; |
|||
right: 0; |
|||
font-size: 14px; |
|||
} |
|||
.left-editor { |
|||
position: relative; |
|||
height: 100%; |
|||
background: #1e1e1e; |
|||
overflow: hidden; |
|||
} |
|||
.setting{ |
|||
position: absolute; |
|||
right: 15px; |
|||
top: 3px; |
|||
color: #a9f122; |
|||
font-size: 18px; |
|||
cursor: pointer; |
|||
z-index: 1; |
|||
} |
|||
.right-preview { |
|||
height: 100%; |
|||
.result-wrapper { |
|||
height: calc(100vh - 33px); |
|||
width: 100%; |
|||
overflow: auto; |
|||
padding: 12px; |
|||
box-sizing: border-box; |
|||
} |
|||
} |
|||
@include action-bar; |
|||
::v-deep .el-drawer__header { |
|||
display: none; |
|||
} |
|||
</style> |
|||
@ -1,144 +0,0 @@ |
|||
<template> |
|||
<div> |
|||
<el-drawer v-bind="$attrs" v-on="$listeners" @opened="onOpen" @close="onClose"> |
|||
<div class="action-bar" :style="{'text-align': 'left'}"> |
|||
<span class="bar-btn" @click="refresh"> |
|||
<i class="el-icon-refresh" /> |
|||
刷新 |
|||
</span> |
|||
<span ref="copyBtn" class="bar-btn copy-json-btn"> |
|||
<i class="el-icon-document-copy" /> |
|||
复制JSON |
|||
</span> |
|||
<span class="bar-btn" @click="exportJsonFile"> |
|||
<i class="el-icon-download" /> |
|||
导出JSON文件 |
|||
</span> |
|||
<span class="bar-btn delete-btn" @click="$emit('update:visible', false)"> |
|||
<i class="el-icon-circle-close" /> |
|||
关闭 |
|||
</span> |
|||
</div> |
|||
<div id="editorJson" class="json-editor" /> |
|||
</el-drawer> |
|||
</div> |
|||
</template> |
|||
|
|||
<script> |
|||
import { beautifierConf } from '@/utils/index' |
|||
import ClipboardJS from 'clipboard' |
|||
import { saveAs } from 'file-saver' |
|||
import loadMonaco from '@/utils/loadMonaco' |
|||
import loadBeautifier from '@/utils/loadBeautifier' |
|||
|
|||
let beautifier |
|||
let monaco |
|||
|
|||
export default { |
|||
components: {}, |
|||
props: { |
|||
jsonStr: { |
|||
type: String, |
|||
required: true |
|||
} |
|||
}, |
|||
data() { |
|||
return {} |
|||
}, |
|||
computed: {}, |
|||
watch: {}, |
|||
created() {}, |
|||
mounted() { |
|||
window.addEventListener('keydown', this.preventDefaultSave) |
|||
const clipboard = new ClipboardJS('.copy-json-btn', { |
|||
text: trigger => { |
|||
this.$notify({ |
|||
title: '成功', |
|||
message: '代码已复制到剪切板,可粘贴。', |
|||
type: 'success' |
|||
}) |
|||
return this.beautifierJson |
|||
} |
|||
}) |
|||
clipboard.on('error', e => { |
|||
this.$message.error('代码复制失败') |
|||
}) |
|||
}, |
|||
beforeDestroy() { |
|||
window.removeEventListener('keydown', this.preventDefaultSave) |
|||
}, |
|||
methods: { |
|||
preventDefaultSave(e) { |
|||
if (e.key === 's' && (e.metaKey || e.ctrlKey)) { |
|||
e.preventDefault() |
|||
} |
|||
}, |
|||
onOpen() { |
|||
loadBeautifier(btf => { |
|||
beautifier = btf |
|||
this.beautifierJson = beautifier.js(this.jsonStr, beautifierConf.js) |
|||
|
|||
loadMonaco(val => { |
|||
monaco = val |
|||
this.setEditorValue('editorJson', this.beautifierJson) |
|||
}) |
|||
}) |
|||
}, |
|||
onClose() {}, |
|||
setEditorValue(id, codeStr) { |
|||
if (this.jsonEditor) { |
|||
this.jsonEditor.setValue(codeStr) |
|||
} else { |
|||
this.jsonEditor = monaco.editor.create(document.getElementById(id), { |
|||
value: codeStr, |
|||
theme: 'vs-dark', |
|||
language: 'json', |
|||
automaticLayout: true |
|||
}) |
|||
// ctrl + s 刷新 |
|||
this.jsonEditor.onKeyDown(e => { |
|||
if (e.keyCode === 49 && (e.metaKey || e.ctrlKey)) { |
|||
this.refresh() |
|||
} |
|||
}) |
|||
} |
|||
}, |
|||
exportJsonFile() { |
|||
this.$prompt('文件名:', '导出文件', { |
|||
inputValue: `${+new Date()}.json`, |
|||
closeOnClickModal: false, |
|||
inputPlaceholder: '请输入文件名' |
|||
}).then(({ value }) => { |
|||
if (!value) value = `${+new Date()}.json` |
|||
const codeStr = this.jsonEditor.getValue() |
|||
const blob = new Blob([codeStr], { type: 'text/plain;charset=utf-8' }) |
|||
saveAs(blob, value) |
|||
}) |
|||
}, |
|||
refresh() { |
|||
try { |
|||
this.$emit('refresh', JSON.parse(this.jsonEditor.getValue())) |
|||
} catch (error) { |
|||
this.$notify({ |
|||
title: '错误', |
|||
message: 'JSON格式错误,请检查', |
|||
type: 'error' |
|||
}) |
|||
} |
|||
} |
|||
} |
|||
} |
|||
</script> |
|||
|
|||
<style lang="scss" scoped> |
|||
@import '@/assets/styles/mixin.scss'; |
|||
|
|||
::v-deep .el-drawer__header { |
|||
display: none; |
|||
} |
|||
@include action-bar; |
|||
|
|||
.json-editor{ |
|||
height: calc(100vh - 33px); |
|||
} |
|||
</style> |
|||
@ -0,0 +1,138 @@ |
|||
<template> |
|||
<div class="preview-form"> |
|||
<div class="" v-if="!formState"> |
|||
<el-row type="flex" justify="center" align="middle"> |
|||
<el-col :sm="{span:20}" :xs="{span:24,offset:0}" style="text-align: center"> |
|||
<h4 class="form-name-text"> |
|||
{{formConf.title}}</h4> |
|||
</el-col> |
|||
</el-row> |
|||
<el-row type="flex" justify="center" align="middle"> |
|||
<el-col :sm="{span:20}" :xs="{span:24,offset:0}" style="text-align: center"> |
|||
<p class="form-name-text"> |
|||
{{formConf.description}} |
|||
</p> |
|||
</el-col> |
|||
</el-row> |
|||
<el-divider></el-divider> |
|||
<parser v-if="formConf.fields.length" :form-conf="formConf" @submit="sumbitForm1"/> |
|||
</div> |
|||
<div v-if="formState"> |
|||
<p style="text-align: center">您已完成本次问卷,感谢您的帮助与支持</p> |
|||
</div> |
|||
</div> |
|||
</template> |
|||
|
|||
<script> |
|||
import Parser from '@/components/parser/Parser' |
|||
import {dbDataConvertForItemJson} from '@/utils/convert' |
|||
// 若parser是通过安装npm方式集成到项目中的,使用此行引入 |
|||
// import Parser from 'form-gen-parser' |
|||
window.onload = function() { |
|||
document.addEventListener('touchstart', function(event) { |
|||
if (event.touches.length > 1) { |
|||
event.preventDefault() |
|||
} |
|||
}) |
|||
document.addEventListener('gesturestart', function(event) { |
|||
event.preventDefault() |
|||
}) |
|||
} |
|||
export default { |
|||
components: { |
|||
Parser |
|||
}, |
|||
props: {}, |
|||
data() { |
|||
return { |
|||
key2: +new Date(), |
|||
formState: false,//是否填写 |
|||
formConf: { |
|||
fields: [], |
|||
__methods__: { |
|||
clickTestButton1() { |
|||
console.log( |
|||
`%c【测试按钮1】点击事件里可以访问当前表单: |
|||
1) formModel='formData', 所以this.formData可以拿到当前表单的model |
|||
2) formRef='elForm', 所以this.$refs.elForm可以拿到当前表单的ref(vue组件) |
|||
`, |
|||
'color:#409EFF;font-size: 15px' |
|||
) |
|||
console.log('表单的Model:', this.formData) |
|||
console.log('表单的ref:', this.$refs.elForm) |
|||
} |
|||
}, |
|||
formRef: 'elForm', |
|||
formModel: 'formData', |
|||
size: 'small', |
|||
labelPosition: 'top', |
|||
labelWidth: 100, |
|||
formRules: 'rules', |
|||
gutter: 15, |
|||
disabled: false, |
|||
span: 24, |
|||
formBtns: true, |
|||
unFocusedComponentBorder: true |
|||
} |
|||
} |
|||
}, |
|||
computed: {}, |
|||
watch: {}, |
|||
created() { |
|||
this.formConf.size = window.innerWidth < 480 ? 'medium' : 'small' |
|||
}, |
|||
mounted() { |
|||
this.$api.get(`/project/query/details/${this.$route.query.key}`).then(res => { |
|||
if (res.data) { |
|||
let fields = res.data.projectItems.map(item => { |
|||
return dbDataConvertForItemJson(item) |
|||
}) |
|||
this.formConf.fields = fields |
|||
this.formConf.title = res.data.project.name |
|||
this.formConf.description = res.data.project.describe |
|||
} |
|||
}) |
|||
}, |
|||
methods: { |
|||
fillFormData(form, data) { |
|||
form.fields.forEach(item => { |
|||
const val = data[item.__vModel__] |
|||
if (val) { |
|||
item.__config__.defaultValue = val |
|||
} |
|||
}) |
|||
}, |
|||
change() { |
|||
this.key2 = +new Date() |
|||
const t = this.formConf |
|||
this.formConf = this.formConf2 |
|||
this.formConf2 = t |
|||
}, |
|||
sumbitForm1(data) { |
|||
console.log('sumbitForm1提交数据:', data) |
|||
this.formState = true |
|||
}, |
|||
sumbitForm2(data) { |
|||
console.log('sumbitForm2提交数据:', data) |
|||
} |
|||
} |
|||
} |
|||
</script> |
|||
|
|||
<style lang="scss" scoped> |
|||
.preview-form { |
|||
margin: 15px auto; |
|||
width: 800px; |
|||
padding: 15px; |
|||
background-repeat: repeat; |
|||
background-color: rgba(229, 239, 247, 0.87); |
|||
} |
|||
|
|||
@media screen and (max-width: 750px) { |
|||
.preview-form { |
|||
margin: 0px; |
|||
width: 93% !important; |
|||
background-color: white; |
|||
} |
|||
} |
|||
</style> |
|||
@ -1,116 +0,0 @@ |
|||
<template> |
|||
<div> |
|||
<el-dialog |
|||
v-bind="$attrs" |
|||
title="外部资源引用" |
|||
width="600px" |
|||
:close-on-click-modal="false" |
|||
v-on="$listeners" |
|||
@open="onOpen" |
|||
@close="onClose" |
|||
> |
|||
<el-input |
|||
v-for="(item, index) in resources" |
|||
:key="index" |
|||
v-model="resources[index]" |
|||
class="url-item" |
|||
placeholder="请输入 css 或 js 资源路径" |
|||
prefix-icon="el-icon-link" |
|||
clearable |
|||
> |
|||
<el-button |
|||
slot="append" |
|||
icon="el-icon-delete" |
|||
@click="deleteOne(index)" |
|||
/> |
|||
</el-input> |
|||
<el-button-group class="add-item"> |
|||
<el-button |
|||
plain |
|||
@click="addOne('https://lib.baomitu.com/jquery/1.8.3/jquery.min.js')" |
|||
> |
|||
jQuery1.8.3 |
|||
</el-button> |
|||
<el-button |
|||
plain |
|||
@click="addOne('https://unpkg.com/http-vue-loader')" |
|||
> |
|||
http-vue-loader |
|||
</el-button> |
|||
<el-button |
|||
icon="el-icon-circle-plus-outline" |
|||
plain |
|||
@click="addOne('')" |
|||
> |
|||
添加其他 |
|||
</el-button> |
|||
</el-button-group> |
|||
<div slot="footer"> |
|||
<el-button @click="close"> |
|||
取消 |
|||
</el-button> |
|||
<el-button |
|||
type="primary" |
|||
@click="handelConfirm" |
|||
> |
|||
确定 |
|||
</el-button> |
|||
</div> |
|||
</el-dialog> |
|||
</div> |
|||
</template> |
|||
<script> |
|||
import { deepClone } from '@/utils/index' |
|||
|
|||
export default { |
|||
components: {}, |
|||
inheritAttrs: false, |
|||
props: ['originResource'], |
|||
data() { |
|||
return { |
|||
resources: null |
|||
} |
|||
}, |
|||
computed: {}, |
|||
watch: {}, |
|||
created() {}, |
|||
mounted() {}, |
|||
methods: { |
|||
onOpen() { |
|||
this.resources = this.originResource.length ? deepClone(this.originResource) : [''] |
|||
}, |
|||
onClose() { |
|||
}, |
|||
close() { |
|||
this.$emit('update:visible', false) |
|||
}, |
|||
handelConfirm() { |
|||
const results = this.resources.filter(item => !!item) || [] |
|||
this.$emit('save', results) |
|||
this.close() |
|||
if (results.length) { |
|||
this.resources = results |
|||
} |
|||
}, |
|||
deleteOne(index) { |
|||
this.resources.splice(index, 1) |
|||
}, |
|||
addOne(url) { |
|||
if (this.resources.indexOf(url) > -1) { |
|||
this.$message('资源已存在') |
|||
} else { |
|||
this.resources.push(url) |
|||
} |
|||
} |
|||
} |
|||
} |
|||
|
|||
</script> |
|||
<style lang="scss" scoped> |
|||
.add-item{ |
|||
margin-top: 8px; |
|||
} |
|||
.url-item{ |
|||
margin-bottom: 12px; |
|||
} |
|||
</style> |
|||
Loading…
Reference in new issue