vue封装选择文件组件和选择文件api
方式一:选择文件组件
<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))
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论