1. 程式人生 > >vue 圖片上傳元件(簡單封裝)

vue 圖片上傳元件(簡單封裝)

import {getUploadImg,saveUploadImg,removeUploadImg} from "../../util/tool/home" export default { props:["orderId",'skuId'] , data() { return { files: [], point: {}, uploading: false, percent: 0, isShowBorder:false
, imgKey:this.orderId ? this.orderId+"_"+this.skuId : this.skuId, imgUrlList:[] } }, methods: { add() { this.isShowBorder=true; this.$refs.file.click(); if(this.files.length>9){ this
.isShowBorder=false; } }, remove(index) { removeUploadImg(this.imgKey, this.files[index]); this.files.splice(index, 1) if(this.files.length<1){ this.isShowBorder=false; } this
.imgUrlList.splice(index, 1) }, mockFileChange(){ const list = this.$refs.file.files for (let i = 0; i < list.length; i++) { if (!this.isContain(list[i])) { const item = { name: list[i].name, size: list[i].size } this.html5Reader(list[i], item) this.files.push(item) saveUploadImg(this.imgKey, item); } } this.$refs.file.value = '' }, fileChanged() { let file = this.$refs.file.files[0]; if(!this.isContain(file)){ const xhr = new XMLHttpRequest() xhr.upload.addEventListener('progress', this.uploadProgress, false) xhr.open('POST', "/uploadImage") this.uploading = true let formData = new FormData() formData.append("file", this.$refs.file.files[0]) xhr.send(formData) xhr.onload = () => { this.uploading = false if (xhr.status === 200 || xhr.status === 304) { let result = JSON.parse(xhr.responseText) console.log('upload success!') if(result.success){ let imgUrl = result.domain + result.imgUrl; const list = this.$refs.file.files for (let i = 0; i < list.length; i++) { const item = { src: imgUrl, name: list[i].name, size:list[i].size } this.files.push(item) saveUploadImg(this.imgKey, item) this.imgUrlList.push(imgUrl) } this.$refs.file.value = '' }else{ console.log("圖片上傳失敗!") } } } }else{ console.log("圖片已選擇!") } }, // 將圖片檔案轉成BASE64格式 html5Reader(file, item){ const reader = new FileReader() reader.onload = (e) => { this.$set(item, 'src', e.target.result) } reader.readAsDataURL(file) }, isContain(file) { return this.files.find((item) => item.name === file.name && item.size === file.size) }, uploadProgress(evt) { const component = this if (evt.lengthComputable) { const percentComplete = Math.round((evt.loaded * 100) / evt.total) component.percent = percentComplete / 100 } else { console.warn('upload progress unable to compute') } }, getCurrentPic(){ return { "skuId":this.skuId, "picList":this.formData } } }, mounted: function() { console.log(this.orderId+","+this.skuId) let stores = getUploadImg(this.imgKey); if(stores){ for(let i=0 ; i<stores.length ;i++){ this.files.push(stores[i]); this.imgUrlList.push(stores[i].src) } } }, watch:{ files(newValue,oldValue){ if(oldValue){ return } console.log(newValue,oldValue) } } }