方式一、选择文件组件
<template>
<div @click="clickHandle">
<slot></slot>
<input type="file" hidden
ref="inputRef"
@change="changeFile"
:accept="accept"
:multiple="multiple"
/>
</div>
</template>
<script>
export default {
name:'ChooseFile',
props:{
accept:{
type:String
},
multiple:{
type:Boolean,
default:false
}
},
methods: {
clickHandle() {
this.$refs.inputRef.click()
},
changeFile(e){
this.$emit('chooseFile',e.target.files)
}
},
}
</script>
<style scoped>
</style>
方式二、选择文件api
const ChooseFile = (options) => {
if(typeof options ==='function'){
options={success:options}
}
if (typeof options === 'object') {
let input = document.createElement("input")
document.body.appendChild(input)
input.type = 'file'
input.hidden='hidden'
if (options.accept) {
input.accept = options.accept
}
if (options.multiple != null) {
input.multiple = options.multiple
}
input.click()
input.onchange = (e) => {
options.success(e.target.files)
document.body.removeChild(input)
}
}
}
export default ChooseFile
挂载在vue原型上
使用
this.$chooseFile((files)=>console.log(files))