vue原生input上传图片

img
需求想做一个这种上传图片的,数量跟随着上方的规格值,但是我循环的话 上传一张图片之后其它的框也是这张图片,应该如何单独上传,求详细解释


   <!-- 图片上传 -->
                <div  style="display: flex;"  >
                    <input v-show="false" type="file" accept="image/*" @change="tirggerFile($event)" ref="input" />
                <div class="uploadBox" @click="openImg" v-for='(item,index) in 2' :key='index' >
                  <span v-if="imgUrl==''" style="font-size:50px;">  
                    <i st slot="default" class="el-icon-plus" style="margin-top:21px"></i>
                  </span>
                  <img style="height:100%;width:100%;" v-if="imgUrl!=''" :src="imgUrl" />
                 </div>
                </div>


        tirggerFile(event) {
                let file = event.target.files[0];
                let url = "";
                var reader = new FileReader();
                reader.readAsDataURL(file);
                let that = this;
                reader.onload = function(e) {
                    url = this.result.substring(this.result.indexOf(",") + 1);
                    that.imgUrl = "data:image/png;base64," + url;
                    // that.$refs['imgimg'].setAttribute('src','data:image/png;base64,'+url);
                };
    },
    openImg() {
      this.$refs.input.click();
    },

既然是循环了 那每个上传input绑定的值肯定是不同值啊,你写个公共的imgUrl 肯定全是同张图

:src="index===0?imgUrl:imgUrl1"

data里定义一个数组变量,比如 imageList,默认是空数组

data() {
  return {
    imageList: []
  }
}

给添加按钮增加一个点击事件,事件处理逻辑:

<template>
  <button @click="onAppend">点击添加一个</button>
</template>

methods: {
  onAppend() {
    this.imageList.push({image: undefined, name: ''})
  }
}

模板里循环 imageList,将输入框和图片上传按钮渲染出来并绑定删除按钮:

<template>
  <div>
    <button @click="onAppend">点击添加一个</button>
    <div v-for="(item, index) of imageList" :key="index">
      <input v-model="item.name"/>
      <input v-model="item.image" type="file"/>
      <i @click="onRemove(index)">我是删除ICON</i>
    </div>
  </div>
</template>

methods: {
  onAppend() {
    this.imageList.push({image: undefined, name: ''})
  },
  onRemove(index) {
    this.imageList.splice(index, 1)
  }
}

你这个代码是封装的组件还是直接在页面中