vue-easy-uploader
一个基于Vue的移动端多文件上传插件,支持常见图片的上传。
特性
- 多文件上传
- 上传图片预览
- 上传状态监测
- 删除指定图片
- 清空图片
- 重新上传
安装
npm i vue-easy-uploader --save
使用
在入口文件main.js
中加入以下代码:
let store = {}Vue
插件内部设置了状态管理,因此需要vuex的支持。
在Vue组件中使用
参数说明
url: 上传接口路径
需要与后端约定上传格式,使用表单提交方式,后端需获取input[type='file']
的name
属性,默认为name="imgFiles[0]"
、name="imgFiles[1]"
...数组序号从0递增。
上传成功时返回的数据如下:
示例代码
<template> <div> <uploader url="http://..." ></uploader> <div class="btn" @click="upload"> 上传 </div> </div></template> <script>import { mapState } from 'vuex'export default { data () { return { imgs: [] } }, computed: { ...mapState({ imgStatus: state => state.imgstore.img_status, imgPaths: state => state.imgstore.img_paths }) }, methods: { upload () { this.$store.commit('set_img_status', 'uploading') }, submit () { let values = [] for (let key of this.imgPaths) { values.push(key) } this.imgs = values console.log(this.imgs) } }, watch: { imgStatus () { if (this.imgStatus === 'finished') { this.submit() } } }, destoryed () { this.imgs = [] }}</script> <style scoped lang="less">.btn { width: 100%; height: 3em; background-color: green; color: #fff; display: flex; justify-content: center; align-items: center;}</style>
状态管理
状态管理存储在state.imgstore中,包括:
state.imgstore.img_upload_cache # 上传文件缓存state.imgstore.img_status # 上传状态,包括 ready selected uploading finishedstate.imgstore.img_paths # 上传后的路径反馈数组(数据结构为Set集合)
img_status
整个上传过程都通过img_status
判断,包括以下几个状态:
ready # 上传开始前的准备状态 selected # 已选择上传文件 uploading # 开始上传 finished # 上传完毕
开始上传
this$store
只需要改变状态管理中的img_status
为uploading
即可。
上传完成
methods: { // some code }computed: ...watch: { if thisimgStatus === 'finished' this }
监视state.imgstore.img_status
,当状态变为finished
时,执行文件上传完成后的回调。
详细的示例可访问本项目的 GitHub地址 。