IT俱乐部 JavaScript vue如何封装选择文件组件和选择文件api

vue如何封装选择文件组件和选择文件api

vue封装选择文件组件和选择文件api

方式一:选择文件组件

1
2
3
<div>
        
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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)
        }
    },
}

方式二:选择文件api

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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原型上

使用

1
this.$chooseFile((files)=>console.log(files))

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持IT俱乐部。

本文收集自网络,不代表IT俱乐部立场,转载请注明出处。https://www.2it.club/navsub/js/13164.html
上一篇
下一篇
联系我们

联系我们

在线咨询: QQ交谈

邮箱: 1120393934@qq.com

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

返回顶部