需求:
用戶可上傳3-6張圖片(第 1 2 3 張必須傳),上傳的圖片必須是540 * 330 像素。
第一步,獲取上傳的圖片的寬高。
初始化一個(gè)對(duì)象數(shù)組,寬高均設(shè)為0。
如果用戶上傳的圖片沒有上限,可以動(dòng)態(tài)修改這個(gè)對(duì)象數(shù)組。
data:
picArray:[ { width:0, height:0 }, { width:0, height:0 }, { width:0, height:0 }, { width:0, height:0 }, { width:0, height:0 }, { width:0, height:0 } ],HTML:
<myupload :keys="index" @getBase="getUpImg"> </myupload>
myupload是上傳圖片的組件,略。
methods:
getUpImg(imgurl, keys){ if(keys === 9){ this.submitData.logo_img = imgurl this.logoImgCount = true } else { Vue.set(this.imgListArray,keys,imgurl) this.$nextTick(function(){ let img = document.getElementById('picId' + keys) // console.log(img) let picArray = this.picArray img.onload = function () { console.log(keys) console.log(this.naturalWidth) console.log(this.naturalHeight) let o = { width: this.naturalWidth, height: this.naturalHeight } Vue.set(picArray,keys,o) console.log('picArray', picArray) } }) } },關(guān)鍵的代碼用紅色標(biāo)出了。
值得注意的是:獲取寬高必須用 this.$nextTick ,里面再寫 img.onload 。this.naturalWidth 是圖片原本的寬高。此時(shí) this 指的是當(dāng)前圖片對(duì)象。
第二步,提交之前檢驗(yàn)圖片的寬高。
methods:
imageCheck(){ let checkboolean = true let check = { 'width': [[540],[0,540]], 'height': [[330],[0,330]] } let f1 = function (num,index,type) { let n = num let i = index let t = type let b = false // console.log(n,i,t) for (let x = 0; x < check[type][i].length; x++) { if (check[type][i][x] === num) { // console.log('>>>>>>>>>>>>>' + check[type][i][x] + '===' + num + '>>>>>>>>>>>>>>>>' ) b = true } } return b } for (let i = 0; i < this.picArray.length; i++) { let cb = true for (let x in this.picArray[i]) { let number = this.picArray[i][x] // console.log(x,number) if (x === 'width' && i < 3) { checkboolean = f1(number, 0, 'width') if (!checkboolean) { // console.log('=================',i,x,number,'return false') cb = false break } } else if (x === 'width' && i >= 3) { checkboolean = f1(number, 1, 'width') if (!checkboolean) { // console.log('=================',i,x,number,'return false') cb = false break } } else if (x === 'height' && i < 3) { checkboolean = f1(number, 0, 'height') if (!checkboolean) { // console.log('=================',i,x,number,'return false') cb = false break } } else if (x === 'height' && i >= 3) { checkboolean = f1(number, 1, 'height') if (!checkboolean) { // console.log('=================',i,x,number,'return false') cb = false break } } } if (!cb) { break } } return checkboolean },// sumbit function... if(!this.imageCheck()){ this.$message({ message: this.MASSAGE_imagecheck, type: 'error' }); return false } alert('可以傳圖')...
新聞熱點(diǎn)
疑難解答
圖片精選