vue如何封装选择文件组件和选择文件api
更新时间:2024年08月30日 17:21:25 作者:Mr阿斌
这篇文章主要介绍了vue如何封装选择文件组件和选择文件api问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
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))
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
Vue全局自适应大小:使用postcss-pxtorem方式
本文介绍了如何在Vue项目中使用postcss-pxtorem插件实现响应式设计,postcss-pxtorem可以自动将CSS文件中的px单位转换为rem单位,从而实现更好的自适应布局,通过配置postcss-pxtorem插件,可以在构建时自动完成转换,无需手动修改代码2025-01-01
使用Webpack提升Vue.js应用程序的4种方法(翻译)
这篇文章主要介绍了使用Webpack提升Vue.js应用程序的4种方法(翻译),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2019-10-10


最新评论