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俱乐部。