vue使用原生<input type=‘file‘/>上传图片并显示缩略图

效果图:
vue使用原生<input type=‘file‘/>上传图片并显示缩略图_第1张图片
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标签强制重新渲染

你可能感兴趣的:(vue,vue,html)