封装之后的使用方法:
import uploadimage from '../components/uploadimage'
=============
components: {
uploadimage: uploadimage,
},
===========
<template>
<uploadimage></uploadimage>
</template>
===============
使用封装之后的调用方法
this.$store.state.imageurls 取上传图片
this.$store.state.upimageurl 取默认展示图片
this.$store.commit('editupimageurl',image) 存默认展示的图片
=============
this.$store.state.imageurls 取上传图片
let imagebot={};
imagebot.value = '123.jpg';
imagebot.label = '123.jpg';
imagebot.uid = '123.jpg';
imagebot.url = value.headUrl
this.$store.commit('editimageurls',imagebot);
存默认展示的图片
==================清除方法
this.$store.commit('editupimageurlzaro','');
this.$store.commit('editimageurlszaro','');
封装为组件uploadFile.vue
html
<el-upload
action="#"
list-type="picture-card"
:before-upload="beforeUpload"
:http-request="beforeUpload"
:file-list="upimageurl"
accept="file"
:on-preview="handlePictureCardPreview"
:on-remove="handleRemove">
<i class="el-icon-plus"></i>
</el-upload>
data变量
upimageurl: [],
imageurls: [],
dialogImageUrl:
dialogVisible: false,
methds 方法
handleRemove(file, fileList) {
let uid=file.uid
const ind=this.imageurls.findIndex((imageobj)=> imageobj.label==uid)
delete this.imageurls[ind]
},
handlePictureCardPreview(file) {
this.dialogImageUrl = file.url
this.dialogVisible = true
},
beforeUpload(file) {
let code = this.$store.state.uploadConfig
let fd = new FormData()
fd.append("file", file)
let uid=file.uid
let url = code.action
// 图片上传
let xhr = new XMLHttpRequest()
xhr.open('POST', url, true)
xhr.setRequestHeader("Authorization", code.token)
// 上传数据成功,会触发
var imagebot={}
var rem=this
xhr.onload = function (e) {
if (xhr.status==200) {
var res = JSON.parse(xhr.responseText)
imagebot.value=res.data
imagebot.label=uid
rem.imageurls.push(imagebot)
}else{
}
}
// 开始上传数据
xhr.upload.onloadstart = function (e) {
}
// 当发生网络异常的时候会触发,如果上传数据的过程还未结束
xhr.upload.onerror = function (e) {
}
// 上传数据完成(成功或者失败)时会触发
xhr.upload.onloadend = function (e) {
// console.log('上传结束')
}
xhr.send(fd)
},