效果图:
在这里插入图片描述
html代码:

	<div class="uploader">
      <input
        type="file"
        class="fonts"
        name=""
        @change="afterRead"
        ref="updata"
        accept="image/*"
        id="upload"
      />
    </div>

    <label for="upload">
      <div class="laber-up">
        <div v-show="src"><img :src="src" alt="" srcset="" /></div>
        <div v-show="!src" ><van-icon name="plus" />
            <p><span class="step-color">点击</span>上传身份证</p>
        </div>
      </div>
    </label>

css代码:

/* 图片上传 */
.uploader {
  display: none;
}
.laber-up {
  width: 100%;
  height: 3.5rem;
  /* background: skyblue; */
  margin-bottom: 0.4rem;
}
.laber-up>div{
    width: 100%;
    height: 100%;
    border: 1px solid #00f;
    border-radius: 5px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    color: #ccc;
    position: relative;
}
.laber-up>div>p{
    font-size: 0.4rem;
    position: absolute;
    top: 2.6rem;
    color: #333;
}
.laber-up>div>img{
    height: 100%;
}
.delog{
    text-align: right;
}

js代码:

<script>
export default {
  data() {
    return {
      src: "",
    };
  },

  methods: {
    afterRead() {
      let that = this;
      
      let file = this.$refs.updata.files[0];
      //   console.log(file);
      var reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = function (e) {
        //   console.log(e);
        that.src = this.result;//显示缩略图
        // console.log(this.result);
      };
    },
  },
};
</script>

选中后清除input所选内容

//重新绑定input的change事件
    resetUploader() {
      //重写一遍input元素
      document.getElementById("upload").outerHTML = document.getElementById(
        "upload"
      ).outerHTML
      //曾经@change="afterRead"绑定的事件解除了,要重新绑定一遍
      document
        .getElementById("upload")
        .addEventListener("change", this.afterRead)
    },

上面的清除方法无效时, 可采用v-if的机制, 使input标签强制重新渲染

Logo

前往低代码交流专区

更多推荐