!36 重构upload组件

Merge pull request !36 from geekreal/develop
This commit is contained in:
就眠儀式 2022-03-27 15:27:39 +00:00 committed by Gitee
commit 8e767faca3
No known key found for this signature in database
GPG Key ID: 173E9B9CA92EEF8F
6 changed files with 266 additions and 346 deletions

View File

@ -13,7 +13,7 @@
::: demo 使用 `lay-upload` 标签, 创建一个按钮上传单文件
<template>
  <lay-upload></lay-upload>
  <lay-upload @done="getUploadFile"/>
</template>
<script>
@ -21,7 +21,32 @@ import { ref } from 'vue'
export default {
  setup() {
const getUploadFile = (file)=>{
console.log(file);
};
    return {
getUploadFile
    }
  }
}
</script>
:::
::: title 多文件上传
:::
::: demo 使用 `lay-upload` 标签, 并使用 `multiple` 创建一个可上传多个文件的上传组件
<template>
  <lay-upload :multiple="true"></lay-upload>
</template>
<script>
import { ref } from 'vue'
export default {
  setup() {
    return {
    }
  }
@ -30,7 +55,7 @@ export default {
:::
::: title 简约按钮
::: title 拖拽上传
:::
::: demo 使用 `lay-upload` 标签, 使用 `drag属性` 创建一个可拖拽的上传文件域
@ -53,292 +78,87 @@ export default {
:::
<!-- ::: title 按钮尺寸
::: title 自定义预览
:::
::: demo 使用 `size` 属性, 创建指定尺寸的按钮, 可选值 `lg` `sm` `xs`
::: demo 使用 `lay-upload` 标签, 使用 `#preview` 自定义预览的UI交互
<template>
<lay-button type="primary" size="lg">原始按钮</lay-button>
<lay-button type="default" size="lg">默认按钮</lay-button>
<lay-button type="normal" size="lg">百搭按钮</lay-button>
<lay-button type="warm" size="lg">暖色按钮</lay-button>
<lay-button type="danger" size="lg">警告按钮</lay-button>
<lay-button type="disabled" size="lg">禁用按钮</lay-button>
  <lay-upload @done="getUploadFile">
<template #preview>
<div class="easy-wrap">
<img src="https://chixian.oss-cn-hangzhou.aliyuncs.com/20211023003617_0706a.jpg" style="width:62.9px;height:63.2px"/>
<img src="https://chixian.oss-cn-hangzhou.aliyuncs.com/20211023003617_0706a.jpg" style="width:62.9px;height:63.2px"/>
<img src="https://chixian.oss-cn-hangzhou.aliyuncs.com/20211023003617_0706a.jpg" style="width:62.9px;height:63.2px"/>
<img src="https://chixian.oss-cn-hangzhou.aliyuncs.com/20211023003617_0706a.jpg" style="width:62.9px;height:63.2px"/>
<img src="https://chixian.oss-cn-hangzhou.aliyuncs.com/20211023003617_0706a.jpg" style="width:62.9px;height:63.2px"/>
</div>
</template>
</lay-upload>
</template>
<script>
import { ref } from 'vue'
export default {
setup() {
return {
}
}
  setup() {
const getUploadFile = (file)=>{
console.log(file);
};
    return {
getUploadFile
    }
  }
}
</script>
:::
::: title 流式按钮
:::
::: demo 使用 `fluid` 属性, 创建最大化按钮
<template>
<lay-button type="primary" fluid>最大化按钮</lay-button>
<br/>
<br/>
<lay-button type="default" fluid>最大化按钮</lay-button>
</template>
<script>
import { ref } from 'vue'
export default {
setup() {
return {
}
}
}
</script>
:::
::: title 圆角按钮
:::
::: demo 使用 `radius` 属性,创建圆角按钮
<template>
<lay-button type="primary" radius>原始按钮</lay-button>
<lay-button type="default" radius>默认按钮</lay-button>
<lay-button type="normal" radius>百搭按钮</lay-button>
<lay-button type="warm" radius>暖色按钮</lay-button>
<lay-button type="danger" radius>警告按钮</lay-button>
<lay-button disabled radius>禁用按钮</lay-button>
</template>
<script>
import { ref } from 'vue'
export default {
setup() {
return {
}
}
}
</script>
:::
::: title 按钮分组
:::
::: demo 使用 `lay-button-group` 标签, 创建一个按钮组
<template>
<div>
<lay-button-group>
<lay-button type="default">默认按钮</lay-button>
<lay-button type="default">默认按钮</lay-button>
<lay-button type="default">默认按钮</lay-button>
</lay-button-group>
<lay-button-group>
<lay-button type="primary">默认按钮</lay-button>
<lay-button type="primary">默认按钮</lay-button>
<lay-button type="primary">默认按钮</lay-button>
</lay-button-group>
</div>
</template>
<script>
import { ref } from 'vue'
export default {
setup() {
return {
}
}
}
</script>
:::
::: title 图标按钮
:::
::: demo 结合 `lay-icon` 组件, 创建图标按钮
<template>
<lay-button-container>
<lay-button type="primary"><lay-icon type="layui-icon-left"></lay-icon></lay-button>
<lay-button type="primary"><lay-icon type="layui-icon-right"></lay-icon></lay-button>
</lay-button-container>
</template>
<script>
import { ref } from 'vue'
export default {
setup() {
return {
}
}
}
</script>
:::
::: title 按钮容器
:::
::: demo 尽管按钮在同节点并排时会自动拉开间距,但在按钮太多的情况,效果并不是很美好。因为你需要用到按钮容器
<template>
<lay-button-container>
<lay-button type="default">新增</lay-button>
<lay-button type="default">删除</lay-button>
<lay-button type="default">修改</lay-button>
</lay-button-container>
</template>
<script>
import { ref } from 'vue'
export default {
setup() {
return {
}
}
}
</script>
:::
::: title 加载按钮
:::
::: demo 使用 `loading` 属性, 控制按钮的加载状态
<template>
<lay-button-container>
<lay-button type="default" :loading="loadState">加载</lay-button>
<lay-switch v-model="loadState"></lay-switch>
</lay-button-container>
</template>
<script>
import { ref } from 'vue'
export default {
setup() {
const loadState = ref(true)
return {
loadState
}
}
}
</script>
:::
::: title 事件处理
:::
::: demo 使用 `@click` 设置单击回调
<template>
<lay-button type="default" @click="clickHandle">单击事件</lay-button>
</template>
<script>
import { ref } from 'vue'
export default {
setup() {
const clickHandle = () => {
console.log('点击事件')
}
return {
clickHandle
}
}
}
</script>
:::
::: title Button 变量
:::
```
```
::: title Button 属性
::: title Upload 属性
:::
::: table
| 属性 | 描述 | 类型 | 默认值 | 可选值 |
| ----------- | -------- | ------- | --------- | ---------------------------------- |
| type | 主题 | string | `primary` | `primary` `normal` `warm` `danger` |
| size | 尺寸 | string | -- | `lg` `sm` `xs` |
| fluid | 最大化 | boolean | `false` | `true` `false` |
| radius | 圆角 | boolean | `false` | `true` `false` |
| border | 边框 | string | `green` | `green` `blue` `orange` `red` |
| disabled | 禁用 | boolean | `false` | `true` `false` |
| loading | 加载 | boolean | `false` | `true` `false` |
| native-type | 原生类型 | string | `button` | `button` `submit` `reset` |
| url | 服务端上传接口,返回的数据规范请详见下文 | string | -- | -- |
| data | 请求上传接口的额外参数 | object | -- | -- |
| headers | 接口的请求头 | object | -- | -- |
| acceptMime | 文件选择框时的可选文件类型 | string | `images` | `images` |
| field | 设定文件域的字段名 | string | `file` | -- |
| size | 设置文件最大可允许上传的大小,单位 KB。不支持ie8/9 | number | `0(不限制)` | -- |
| multiple | 是否允许多文件上传。设置 true即可开启。不支持ie8/9 | boolean | false | -- |
| number | 设置同时可上传的文件数量,一般配合 multiple 参数出现。 | number | `0(不限制)` | -- |
| drag | 是否接受拖拽的文件上传,设置 false 可禁用。不支持ie8/9 | boolean | true | -- |
:::
::: title Button 插槽
::: title Upload 插槽
:::
::: table
| 名称 | 描述 | 参数 |
| ------- | -------- | ---- |
| default | 默认内容 | -- |
| preview | 自定义预览效果 | -- |
:::
::: title Button Group 属性
::: title Upload 事件
:::
::: table
| 属性 | 描述 | 类型 | 默认值 | 可选值 |
| ---- | ---- | ---- | ------ | ------ |
| - | - | - | - |
:::
::: title Button Group 插槽
:::
::: table
| 事件 | 描述 | 参数 |
| 名称 | 描述 | 参数 |
| ------- | -------- | ---- |
| default | 默认内容 | -- |
| choose | 打开系统选择文件窗体的回调 | -- |
| before | 上传事务开启前的回调 | -- |
| done | 上传事务结束的回调 | -- |
| error | 上传事务中出现错误的回调 | -- |
:::
::: comment
:::
::: previousNext button
::: -->

View File

@ -297,6 +297,12 @@ const zhCN = [
import("../../docs/zh-CN/components/datePicker.md"),
meta: { title: "日期选择器" },
},
{
path: "/zh-CN/components/upload",
component: () =>
import("../../docs/zh-CN/components/upload.md"),
meta: { title: "文件上传" },
},
{
path: "/zh-CN/components/layer",
component: () => import("../../docs/zh-CN/components/layer.md"),

View File

@ -176,6 +176,12 @@ const menus = [
subTitle: "datePicker",
path: "/zh-CN/components/datePicker",
},
{
id: 40,
title: "文件上传",
subTitle: "upload",
path: "/zh-CN/components/upload",
},
{
id: 29,
title: "图标选择器",

View File

@ -1,11 +1,17 @@
@import "../../theme/variable.less";
.layui-upload-file {
display: none !important;
// display: none !important;
opacity: 0.01;
position: relative;
filter: Alpha(opacity=1);
cursor: pointer;
}
.layui-upload-btn-box{
position:relative;
overflow: hidden;
}
.layui-upload-drag,
.layui-upload-form,
.layui-upload-wrap {
@ -44,6 +50,9 @@
.layui-upload-drag[lay-over] {
border-color: @global-primary-color;
}
.layui-upload-drag-draging{
border-color: @global-primary-color;
}
.layui-upload-iframe {
position: absolute;
@ -56,6 +65,7 @@
.layui-upload-wrap {
position: relative;
vertical-align: middle;
cursor: pointer;
}
.layui-upload-wrap .layui-upload-file {
@ -65,8 +75,8 @@
top: 0;
z-index: 10;
font-size: 100px;
width: 100%;
height: 100%;
width: 1px;
height: 1px;
opacity: 0.01;
filter: Alpha(opacity=1);
cursor: pointer;

View File

@ -6,121 +6,195 @@ export default {
<script lang="ts" setup>
import "./index.less";
import { Recordable } from "../../types";
import { ref, watch, useSlots, withDefaults, onMounted } from "vue";
import { layer } from "@layui/layer-vue";
import { ref, useSlots, withDefaults, onMounted, defineExpose } from "vue";
import { templateRef } from "@vueuse/core";
//
//https://www.layuiweb.com/doc/modules/upload.html#options
export interface LayUploadProps {
elem?: string | HTMLElement;
url?: string;
data?: Recordable;
data?: any;
headers?: Recordable;
accept?: "images" | "file" | "video" | "audio";
acceptMime?: "images" | "file" | "video" | "audio";
exts?: "jpg" | "png" | "gif" | "bmp" | "jpeg";
auto?: boolean;
bindAction?: string | HTMLElement;
field?: string;
size?: number;
multiple?: boolean;
number: number;
drag?: boolean;
}
const props = withDefaults(defineProps<LayUploadProps>(), {
accept: "images",
acceptMime: "images",
auto: true,
field: "file",
size: 0,
multiple: false,
number: 0,
drag: false,
});
const emit = defineEmits(["choose", "before", "done", "error"]);
const slot = useSlots();
const slots = slot.default && slot.default();
const emit = defineEmits(["choose", "before", "done", "error"]);
//
const isDragEnter = ref(false);
const orgFileInput = templateRef<HTMLElement>("orgFileInput");
//
const defaultErrorMsg = "上传失败";
const urlErrorMsg = "上传地址格式不合法";
const numberErrorMsg = "文件上传超过规定的个数";
const sizeErrorMsg = "文件大小超过限制";
const uploadRemoteErrorMsg = "请求上传接口出现异常";
const uploadSuccess = "上传成功";
// -> start
//
interface localUploadTransaction {
url: string;
files: File[] | Blob[];
[propMame: string]: any;
}
const localUploadTransaction = (option: localUploadTransaction) => {
const { url, files } = option;
let formData = new FormData();
if (url.length <= 5) {
errorF(urlErrorMsg);
return;
}
if (Array.isArray(files) && files.length > 0) {
for (let i = 0; i < files.length; i++) {
let _file = files[i];
formData.append("file[" + i + "]", _file);
}
// Uploaddata,
if (props.data && props.data instanceof Object) {
let _requestDate = props.data;
for (const key in _requestDate) {
formData.append(key, _requestDate[key]);
}
}
let utimer = window.setTimeout(() => {
localUpload({ url, formData }, function () {
clearTimeout(utimer);
});
}, 200);
}
};
//
interface localUploadOption {
url: string;
file?: unknown;
otherRequestData?: any;
[propMame: string]: any;
}
const localUpload = (option: any) => {
let file,
formData,
xhr: XMLHttpRequest,
loadedevt,
total,
per: number,
url,
uploading;
formData = new FormData();
const errorF = (errorText: string) => {
let currentTimeStamp = new Date().valueOf();
let errorMsg = errorText ? errorText : defaultErrorMsg;
errorMsg = `layui-vue:${errorMsg}`;
console.warn(errorMsg);
layer.msg(errorMsg, { icon: 2, time: 1000 }, function (res: unknown) {});
emit("error", Object.assign({ currentTimeStamp, msg: errorMsg }));
};
const localUpload = (option: localUploadOption, callback: Function) => {
let xhr: XMLHttpRequest, loadedevt, total, per: number, url, uploading;
xhr = new XMLHttpRequest();
url = option.url;
file = option.file;
formData.append("files", file);
//append
if (option.otherRequestData instanceof Object) {
var _requestDate = option.otherRequestData;
for (var key in _requestDate) {
formData.append(key, _requestDate[key]);
}
}
let formData = option.formData;
const cb = callback;
//
// event callbacks
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if ((xhr.status >= 200 && xhr.status <= 300) || xhr.status === 304) {
option.successF instanceof Function &&
option.successF(xhr.responseText);
let currentTimeStamp = new Date().valueOf();
let successText = xhr.responseText ? xhr.responseText : uploadSuccess;
emit(
"before",
Object.assign({ currentTimeStamp, msg: successText, ...option })
);
} else {
option.errorF instanceof Function && option.errorF(xhr.responseText);
errorF(xhr.responseText);
}
} else {
option.errorF instanceof Function && option.errorF();
errorF(defaultErrorMsg);
}
};
//
/**
* 附件的上传进度条方法在xhr.upload.onprogeress上
* 还有一个xhr.onprogress,是下载时候的进度条,***
* */
xhr.upload.onprogress = function (event) {
// event.totalevent.loadedevent.lengthComputableevent.total0
if (event.lengthComputable) {
loadedevt = event.loaded;
total = event.total;
per = Math.floor((100 * loadedevt) / total);
}
//
option.uploadProgress instanceof Function && option.uploadProgress(per);
};
xhr.open("post", url, true); //GET, getURL
xhr.setRequestHeader("Accept", "application/json, text/javascript");
// Uploadheaders,
if (props.headers) {
for (let key in props.headers) {
xhr.setRequestHeader(key, props.headers[key]);
}
} else {
xhr.setRequestHeader("Accept", "application/json, text/javascript");
}
//
let currentTimeStamp = new Date().valueOf();
emit("before", Object.assign(option, currentTimeStamp));
xhr.send(formData);
if (cb && typeof cb == "function") {
cb();
}
};
const getUploadChange = (e: any) => {
// console.log(e.srcElement);
const file = e.target.files[0];
console.log(file);
const files = e.target.files;
const _files = [...files];
// Uploadnumber,
if (props.multiple && props.number != 0 && props.number < _files.length) {
errorF(numberErrorMsg);
return;
}
// Uploadsize,
if (props.size && props.size != 0) {
let _cache = [];
for (let i = 0; i < _files.length; i++) {
let _file = _files[i];
let _size = _file.size;
if (_size > props.size * 1024) {
_cache.push(_file);
}
}
if (_cache && _cache.length > 0) {
for (let i = 0; i < _cache.length; i++) {
let _sizeErrorFile = _cache[i];
let errorMsg = `文件 ${
_sizeErrorFile.name
} ${sizeErrorMsg},文件最大不可超过${props.size * 1000}kb`;
errorF(errorMsg);
}
}
}
if (props.url) {
//
localUpload({
localUploadTransaction({
url: props.url,
file: file,
files: _files,
});
} else {
//
//
emit("done", _files);
}
};
const uploadDragOver = (e: any) => {
//console.log("uploadDrag9ikme",e);
const chooseFile = () => {
console.log(orgFileInput.value);
let _target = orgFileInput.value;
if (_target) {
_target.click();
}
// _target?.onclick();
};
const clickOrgInput = () => {
let currentTimeStamp = new Date().valueOf();
//console.log(currentTimeStamp);
emit("choose", currentTimeStamp);
};
const uploadDragOver = (e: any) => {};
const uploadDragDrop = (e: any) => {
isDragEnter.value = false;
console.log(e);
};
const uploadDragStop = (e: any) => {};
const uploadDragEnter = (e: any) => {
@ -129,46 +203,47 @@ const uploadDragEnter = (e: any) => {
const uploadDragLeave = (e: any) => {
isDragEnter.value = false;
};
// -> end
</script>
<template>
<div class="layui-upload" v-if="!drag">
<div class="layui-upload-btn-box">
<button type="button" class="layui-btn">上传图片</button>
<input
class="layui-upload-file"
:multiple="multiple"
type="file"
:accept="accept"
:name="field"
@change="getUploadChange"
/>
</div>
<div class="layui-upload-list">
<img class="layui-upload-img" id="demo1" />
<p id="demoText"></p>
</div>
</div>
<div
v-else
class="layui-upload-drag"
:class="isDragEnter ? 'layui-upload-drag-draging' : ''"
@dragleave.stop="uploadDragLeave"
@dragenter.stop="uploadDragEnter"
@dragover.stop="uploadDragOver"
@drop="uploadDragDrop"
>
<i class="layui-icon"></i>
<p>点击上传或将文件拖拽到此处</p>
<div class="layui-hide" id="uploadDemoView">
<hr />
<img src="" alt="上传成功后渲染" style="max-width: 196px" />
</div>
<div class="layui-upload layui-upload-wrap">
<input
class="layui-upload-file"
@click="clickOrgInput"
:multiple="multiple"
type="file"
:accept="accept"
:accept="acceptMime"
:name="field"
@change="getUploadChange"
/>l
:field="field"
ref="orgFileInput"
/>
<div v-if="!drag">
<div class="layui-upload-btn-box">
<lay-button type="primary" @click.stop="chooseFile"
>上传图片</lay-button
>
</div>
</div>
<div
v-else
class="layui-upload-drag"
:class="isDragEnter ? 'layui-upload-drag-draging' : ''"
@dragleave.stop="uploadDragLeave"
@dragenter.stop="uploadDragEnter"
@dragover.stop="uploadDragOver"
@drop="uploadDragDrop"
@click.stop="chooseFile"
>
<i class="layui-icon"></i>
<p>点击上传或将文件拖拽到此处</p>
<div class="layui-hide" id="uploadDemoView">
<hr />
<img src="" alt="上传成功后渲染" style="max-width: 196px" />
</div>
</div>
<div class="layui-upload-list">
<slot name="preview"></slot>
</div>
</div>
</template>

View File

@ -81,6 +81,7 @@ import LayFullscreen from "./component/fullscreen/index";
import LayDatePicker from "./component/datePicker/index";
import LayNoticeBar from "./component/noticeBar/index";
import LayTransition from "./component/transition/index";
import LayUpload from "./component/upload/index";
import LayConfigProvider from "./provider";
import { InstallOptions } from "./types";
@ -160,6 +161,7 @@ const components: Record<string, Component> = {
LayDatePicker,
LayNoticeBar,
LayTransition,
LayUpload,
};
const install = (app: App, options?: InstallOptions): void => {
@ -247,6 +249,7 @@ export {
LayDatePicker,
LayNoticeBar,
LayTransition,
LayUpload,
};
export { layer };