鍍金池/ 問(wèn)答/Java  HTML/ vue.js刪除預(yù)覽圖片無(wú)效問(wèn)題。

vue.js刪除預(yù)覽圖片無(wú)效問(wèn)題。

vue.js小白,正在嘗試做一個(gè)多圖預(yù)覽刪除并上傳的功能,已經(jīng)實(shí)現(xiàn)了單圖上傳預(yù)覽,刪除還遇到些問(wèn)題,希望大牛們指點(diǎn)迷津,附上html,vue.js的代碼。
主要問(wèn)題:選擇多圖預(yù)覽時(shí)只顯示單圖,刪除單圖時(shí)不知道如何獲取圖片的索引,嘗試用過(guò)v-for,但是在<div class="col-sm-10">中加上v-for="(key,image) in images"圖片預(yù)覽就不成功
html:

            <div class="form-group">
                <div class="col-sm-2 control-label">圖片預(yù)覽</div>
                <div class="col-sm-10">
                    <img src="image" id="pic" style="height: 267px; width: 267px;"/>
                    <a href="#"
                            style="position: absolute;" @click='delImage(key)'> 
                            <span class="glyphicon glyphicon-remove"></span>
                    </a>
                    <button @click="removeImage">移除全部圖片</button>
                    <button @click='uploadImage'>上傳</button>
                </div>
            </div>

            <div class="form-group">
                <div class="col-sm-2 control-label">圖片上傳</div>
                <div class="col-sm-10">
                <input type="file" id="uploadFile" name="uploadFile" @change="onFileChange" multiple="multiple" class="form-control" >
                </div>
            </div>

vue.js:

    onFileChange(e) {
        var files = e.target.files || e.dataTransfer.files;
        if (!files.length)
        return; 
        this.createImage(files);
    },
    createImage(file) {
        var image = new Image();         
        var vm = this;
        var leng=file.length;
        for(var i=0;i<leng;i++){
            var reader = new FileReader();
            var uploadFile  = document.getElementById("uploadFile").files[0];
            reader.readAsDataURL(uploadFile);
            reader.onload =function(e){
                  $("#pic").attr("src", e.target.result);
            };                 
        }
    },
    delImage:function(index){
        this.images.shift(index);
        
    },
    removeImage: function(e) {

// this.images = [];

        $("#pic").remove();
    },
回答
編輯回答
離夢(mèng)

1.先創(chuàng)建一個(gè)全局變量,用于存儲(chǔ)與圖片有關(guān)的信息。

this.imgs = [];

2.在createImage()方法中,每次選擇圖片后對(duì)imgs進(jìn)行設(shè)置。

for () {
  this.imgs.push({
    file: files[i],
    dataUrl: e.target.result
  });
}

——————能完成這一步,之后就簡(jiǎn)單了。———————

3.比如要預(yù)覽全部圖片。

<div v-for="img in imgs">
  <img />
  <button />
</div>

4.比如刪除某張圖片。

removeImg(index) {
  this.imgs.splice(index, 1);
}

5.最后要整體上傳。

let formData = new FormData();
this.imgs.forEach((img, i) => {
  formData.appendData('img' + i, img);
});
2017年9月3日 07:52
編輯回答
心癌

樓上說(shuō)得很詳細(xì)了,我只好來(lái)找點(diǎn)問(wèn)題

  1. 最好不要vue和jquery混用
  2. shift(index)是什么鬼,應(yīng)該是splice(index,1)吧
2017年7月12日 05:35