<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>
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))
以上为个人经验,希望对您有所帮助。