yudao-dev/src/components/DialogForm/index.vue

448 lines
10 KiB
Vue
Raw Normal View History

2023-08-11 16:49:28 +08:00
<!--
filename: dialogForm.vue
author: liubin
2023-08-15 14:57:10 +08:00
date: 2023-08-15 10:32:36
2023-08-11 16:49:28 +08:00
description: 弹窗的表单组件
-->
<template>
<el-form
ref="form"
:model="form"
:label-width="`${labelWidth}px`"
2023-10-12 11:08:51 +08:00
:size="size"
:label-position="labelPosition"
2023-08-11 16:49:28 +08:00
v-loading="formLoading">
<el-row :gutter="20" v-for="(row, rindex) in rows" :key="rindex">
<el-col v-for="col in row" :key="col.label" :span="24 / row.length">
<el-form-item :label="col.label" :prop="col.prop" :rules="col.rules">
<el-input
v-if="col.input"
v-model="form[col.prop]"
@change="$emit('update', form)"
:placeholder="`请输入${col.label}`"
v-bind="col.bind" />
<el-input
v-if="col.textarea"
type="textarea"
v-model="form[col.prop]"
@change="$emit('update', form)"
:placeholder="`请输入${col.label}`"
v-bind="col.bind" />
<el-select
v-if="col.select"
v-model="form[col.prop]"
:placeholder="`请选择${col.label}`"
@change="$emit('update', form)"
v-bind="col.bind">
<el-option
v-for="opt in optionListOf[col.prop]"
:key="opt.value"
:label="opt.label"
:value="opt.value" />
</el-select>
<el-date-picker
v-if="col.datetime"
v-model="form[col.prop]"
type="datetime"
:placeholder="`请选择${col.label}`"
2023-08-22 15:53:02 +08:00
value-format="timestamp"
2023-08-11 16:49:28 +08:00
v-bind="col.bind"></el-date-picker>
2023-09-01 10:39:54 +08:00
<el-switch
v-if="col.switch"
v-model="form[col.prop]"
active-color="#0b58ff"
inactive-color="#e1e1e1"
v-bind="col.bind"></el-switch>
2023-08-18 16:56:53 +08:00
<component
v-if="col.subcomponent"
:key="col.key"
:is="col.subcomponent"
2023-08-24 15:36:38 +08:00
:inlineStyle="col.style"></component>
2023-10-16 17:03:29 +08:00
<div
class="upload-area"
:class="uploadOpen ? '' : 'height-48'"
ref="uploadArea"
v-if="col.upload">
<span class="close-icon" :class="uploadOpen ? 'open' : ''">
<el-button
type="text"
icon="el-icon-arrow-right"
@click="handleFilesOpen" />
</span>
<!-- :file-list="uploadedFileList" -->
<el-upload
class="upload-in-dialog"
v-if="col.upload"
:action="uploadUrl"
:headers="uploadHeaders"
:show-file-list="false"
icon="el-icon-upload2"
:before-upload="beforeUpload"
:on-success="handleUploadSuccess"
v-bind="col.bind">
<el-button size="mini" :disabled="col.bind?.disabled || false">
2023-10-17 17:02:53 +08:00
<svg-icon
icon-class="icon-upload"
style="color: inherit"></svg-icon>
2023-10-16 17:03:29 +08:00
上传文件
</el-button>
<div class="el-upload__tip" slot="tip" v-if="col.uploadTips">
{{ col.uploadTips || '只能上传jpg/png文件, 大小不超过2MB' }}
</div>
</el-upload>
<uploadedFile
class="file"
v-for="file in form[col.prop] || []"
:file="file"
2023-10-17 15:22:17 +08:00
:key="file.fileUrl"
2023-10-16 17:03:29 +08:00
@delete="handleDeleteFile(file)" />
</div>
2023-08-11 16:49:28 +08:00
</el-form-item>
</el-col>
</el-row>
</el-form>
</template>
<script>
2023-10-16 17:03:29 +08:00
import { getAccessToken } from '@/utils/auth';
import tupleImg from '@/assets/images/tuple.png';
2023-10-20 14:22:46 +08:00
import cache from '@/views/extend/processFlow/cache';
2023-10-16 17:03:29 +08:00
2023-08-11 16:49:28 +08:00
/**
* 找到最长的label
* @param {*} options
*/
function findMaxLabelWidth(rows) {
let max = 0;
rows.forEach((row) => {
row.forEach((opt) => {
2023-10-09 16:27:44 +08:00
// debugger;
if (!opt.label) return 0;
2023-08-11 16:49:28 +08:00
if (opt.label.length > max) {
max = opt.label.length;
}
});
});
return max;
}
2023-10-16 17:03:29 +08:00
const uploadedFile = {
name: 'UploadedFile',
props: ['file'],
data() {
return {};
},
methods: {
handleDelete() {
this.$emit('delete', this.file);
},
},
mounted() {},
render: function (h) {
return (
<div
title={this.file.fileName}
style={{
background: `url(${tupleImg}) no-repeat`,
backgroundSize: '14px',
backgroundPosition: '0 55%',
paddingLeft: '20px',
paddingRight: '24px',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
overflow: 'hidden',
cursor: 'pointer',
display: 'inline-block',
}}>
{this.file.fileName}
<el-button
type="text"
icon="el-icon-close"
style="float: right; position: relative; top: 2px; left: 8px; z-index: 100"
class="dialog__upload_component__close"
onClick={this.handleDelete}
/>
</div>
);
},
};
2023-08-11 16:49:28 +08:00
export default {
name: 'DialogForm',
model: {
prop: 'dataForm',
event: 'update',
},
emits: ['update'],
2023-10-16 17:03:29 +08:00
components: { uploadedFile },
2023-08-11 16:49:28 +08:00
props: {
rows: {
type: Array,
default: () => [],
},
dataForm: {
type: Object,
default: () => ({}),
},
2023-10-10 14:22:00 +08:00
disabled: {
type: Boolean,
default: false,
2023-10-12 11:08:51 +08:00
},
2023-10-20 14:22:46 +08:00
hasFiles: {
type: Boolean,
default: false,
},
2023-10-12 11:08:51 +08:00
labelPosition: {
type: String,
default: 'right',
},
size: {
type: String,
default: '',
},
2023-08-11 16:49:28 +08:00
},
data() {
return {
2023-10-16 17:03:29 +08:00
uploadOpen: false,
form: {},
2023-08-11 16:49:28 +08:00
formLoading: true,
optionListOf: {},
2023-08-15 14:57:10 +08:00
uploadedFileList: [],
2023-08-28 13:30:29 +08:00
dataLoaded: false,
2023-10-16 17:03:29 +08:00
uploadHeaders: { Authorization: 'Bearer ' + getAccessToken() },
uploadUrl: process.env.VUE_APP_BASE_API + '/admin-api/infra/file/upload', // 上传有关的headersurl都是固定的
2023-08-11 16:49:28 +08:00
};
},
computed: {
labelWidth() {
let max = findMaxLabelWidth(this.rows);
// 每个汉字占20px
return max * 20;
// return max * 20 + 'px';
},
},
watch: {
rows: {
handler() {
this.$nextTick(() => {
this.handleOptions('watch');
});
},
deep: true,
immediate: false,
},
2023-10-16 17:03:29 +08:00
dataForm: {
handler(val) {
this.form = JSON.parse(JSON.stringify(val));
2023-10-20 14:22:46 +08:00
if (this.hasFiles) {
this.form.files = this.form.files ?? [];
}
2023-10-16 17:03:29 +08:00
},
deep: true,
immediate: true,
},
2023-08-11 16:49:28 +08:00
},
mounted() {
// 处理 options
this.handleOptions();
},
methods: {
/** 模拟透传 ref */
validate(cb) {
return this.$refs.form.validate(cb);
},
resetFields(args) {
return this.$refs.form.resetFields(args);
},
// getCode
async getCode(url) {
const response = await this.$axios(url);
return response.data;
},
async handleOptions(trigger = 'monuted') {
2023-08-28 13:30:29 +08:00
console.log('[dialogForm:handleOptions]');
2023-08-11 16:49:28 +08:00
const promiseList = [];
this.rows.forEach((cols) => {
cols.forEach((opt) => {
if (opt.value && !this.form[opt.prop]) {
// 默认值
this.form[opt.prop] = opt.value;
}
if (opt.options) {
this.$set(this.optionListOf, opt.prop, opt.options);
} else if (opt.url) {
2023-08-28 09:22:28 +08:00
// 如果有 depends则暂时先不获取注册一个watcher
if (opt.depends) {
2023-08-28 13:30:29 +08:00
console.log('[handleOptions] setting watch');
2023-08-28 09:22:28 +08:00
this.$watch(
() => this.form[opt.depends],
(id) => {
2023-08-28 13:30:29 +08:00
console.log('<', opt.depends, '>', 'changed', id);
if (id == null) return;
2023-08-28 09:22:28 +08:00
// 清空原有选项
this.form[opt.prop] = null;
// 获取新的选项
this.$axios({
url: `${opt.url}?id=${id}`,
}).then((res) => {
this.$set(
this.optionListOf,
opt.prop,
res.data.map((item) => ({
label: item[opt.labelKey ?? 'name'],
value: item[opt.valueKey ?? 'id'],
}))
);
});
2023-08-28 13:30:29 +08:00
},
{
immediate: true,
2023-08-28 09:22:28 +08:00
}
);
return;
}
2023-08-11 16:49:28 +08:00
// 如果是下拉框,或者新增模式下的输入框,才去请求
if (opt.select || (opt.input && !this.form?.id)) {
promiseList.push(async () => {
const response = await this.$axios(opt.url, {
method: opt.method ?? 'get',
});
console.log('[dialogForm:handleOptions:response]', response);
if (opt.select) {
// 处理下拉框选项
const list =
'list' in response.data
? response.data.list
: response.data;
2023-10-20 14:22:46 +08:00
if (opt.cache) {
cache.store(opt.cache, list);
}
2023-08-11 16:49:28 +08:00
this.$set(
this.optionListOf,
opt.prop,
list.map((item) => ({
label: item[opt.labelKey ?? 'name'],
value: item[opt.valueKey ?? 'id'],
}))
);
} else if (opt.input) {
2023-09-01 10:39:54 +08:00
console.log('setting code: ', response.data);
2023-08-11 16:49:28 +08:00
// 处理输入框数据
this.form[opt.prop] = response.data;
}
});
}
}
});
});
2023-08-28 13:30:29 +08:00
console.log('[dialogForm:handleOptions] done!');
2023-08-11 16:49:28 +08:00
// 如果是 watch 触发的,不需要执行进一步的请求
if (trigger == 'watch') {
this.formLoading = false;
return;
}
try {
await Promise.all(promiseList.map((fn) => fn()));
this.formLoading = false;
2023-08-28 13:30:29 +08:00
this.dataLoaded = true;
2023-08-11 16:49:28 +08:00
// console.log("[dialogForm:handleOptions:optionListOf]", this.optionListOf)
} catch (error) {
console.log('[dialogForm:handleOptions:error]', error);
this.formLoading = false;
}
if (!promiseList.length) this.formLoading = false;
},
2023-08-15 14:57:10 +08:00
// 上传成功的特殊处理
2023-08-28 09:22:28 +08:00
beforeUpload() {},
2023-08-15 14:57:10 +08:00
// 上传前的验证规则可通过 bind 属性传入
handleUploadSuccess(response, file, fileList) {
2023-10-16 17:03:29 +08:00
this.form.files.push({
fileName: file.name,
fileUrl: response.data,
fileType: 2,
});
2023-08-15 14:57:10 +08:00
this.$modal.msgSuccess('上传成功');
2023-10-16 17:03:29 +08:00
this.$emit('update', this.form);
2023-08-15 14:57:10 +08:00
},
getFileName(fileUrl) {
return fileUrl.split('/').pop();
2023-08-18 16:56:53 +08:00
},
2023-10-16 17:03:29 +08:00
handleFilesOpen() {
this.uploadOpen = !this.uploadOpen;
},
handleDeleteFile(file) {
2023-10-20 14:22:46 +08:00
this.form.files = this.form.files.filter(
(item) => item.fileUrl != file.fileUrl
);
2023-10-16 17:03:29 +08:00
this.$emit('update', this.form);
},
2023-08-11 16:49:28 +08:00
},
};
</script>
<style scoped lang="scss">
.el-date-editor,
.el-select {
width: 100%;
}
2023-10-16 17:03:29 +08:00
.upload-area {
// background: #ccc;
// display: grid;
// grid-auto-rows: 34px;
// grid-template-columns: repeat(6, minmax(32px, max-content));
// gap: 8px;
// align-items: center;
position: relative;
overflow: hidden;
transition: height 0.3s ease-out;
}
.upload-in-dialog {
// display: inline-block;
margin-right: 24px;
// background: #ccc;
position: relative;
// top: -13px;
float: left;
}
.close-icon {
// background: #ccc;
position: absolute;
top: 0;
right: 12px;
z-index: 100;
transition: transform 0.3s ease-out;
}
.close-icon.open {
transform: rotateZ(90deg);
}
</style>
<style>
.dialog__upload_component__close {
color: #ccc;
}
.dialog__upload_component__close:hover {
/* color: #777; */
color: red;
}
.height-48 {
height: 35px !important;
}
2023-08-11 16:49:28 +08:00
</style>