magiccube-vue3
Version:
vue3-js版组件库
125 lines (117 loc) • 3.83 kB
JavaScript
import { ref } from 'vue'
import post from './ajax'
const Import = {
name: 'McImport',
props: {
name: {
type: String,
default: 'file'
},
multiple: Boolean,
accept: String,
// 上传地址
action: {
type: String,
required: true
},
//上传时额外参数
extraParams: {
type: Object,
default: () => {}
},
//请求头
headers: {
type: Object,
default: () => {}
},
// with-credentials 支持发送 cookie 凭证信息
withCredentials: {
type: Boolean,
default: true,
},
filename: String,
//文件上传成功时的钩子
onSuccess: {
type: Function,
default: () => {}
},
onError: {
type: Function,
default: () => {}
},
beforeUpload: Function
},
emits: [],
setup(props, { emit, slots }) {
const input = ref(null)
const handleChange = (ev) => {
const files = ev.target.files
if(!files) return
let postFiles = Array.prototype.slice.call(files)
if(!props.multiple) postFiles = postFiles.slice(0, 1)
if(postFiles.length === 0) return false
if(props.multiple){
uploadFiles(postFiles)
} else {
uploadFiles(postFiles[0])
}
}
/* 导入前的文件处理 */
const uploadFiles = (rawFile) => {
if(props.beforeUpload && typeof props.beforeUpload === 'function'){
props.beforeUpload(rawFile, status => {
if(status) {
handleUpload(rawFile)
} else {
if(input.value) input.value.value = ''
}
})
} else {
handleUpload(rawFile)
}
}
const handleUpload = (rawFile) => {
const options = {
// 请求头中加入的header,加入的header信息用来配合请求的action做一些处理,比如携带token给后台
headers: props.headers,
// 布尔值,用来指定跨域 Access-Control 请求是否应带有授权信息,如 cookie 或授权 header 头。
withCredentials: props.withCredentials,
file: rawFile,
multi: props.multiple,
// 需要传给后台的一些入参
extraParams: props.extraParams,
filename: props.filename,
// 上传的地址
action: props.action,
// 文件上传成功时的钩子
onSuccess: res => {
if(input.value) input.value.value = ''
props.onSuccess(res, rawFile)
},
// 文件上传失败时的钩子
onError: err => {
if(input.value) input.value.value = ''
props.onError(err, rawFile)
}
}
post(options)
}
return () => (
<div class="mc-import">
<input class="mc-import__input"
ref={input}
type="file"
name={props.name}
accept={props.accept}
onChange={handleChange}
multiple={props.multiple} />
{slots.default? slots.default() : ''}
</div>
)
}
}
Import.install = (app) => {
app.component(Import.name, Import)
}
const McImport = Import
export { McImport, McImport as default }