Bootstrap

vue 图片放大缩小旋转以及下载

效果图:

使用组件el-image,使用前检查element-ui版本,2.4.6以下请升级新版本

卸载element-ui:

npm uninstall element-ui

下载element-ui:

 npm i element-ui -S  

1.img标签替换成el-image

<el-image
              class="avatar"
              :src="image.imagePath"
              :fit="fit"
              :preview-src-list="imageList"
              :scroll-container="scrollContainer"
              lazy
              @click="clickImage"
            ></el-image>

注:src替换成自己的

2.data中初始化属性

data(){
return {
scrollContainer: HTMLCollection,
fit: "fill",
wrapperElem: null,
imageList: [] // 获取的数据
}
}

3.方法

clickImage() {
      this.$nextTick(() => {
        let wrapper = document.getElementsByClassName(
          "el-image-viewer__actions__inner"
        );
        let downImg = document.createElement("i");
        downImg.setAttribute("class", "el-icon-download");
        wrapper[0].appendChild(downImg);
        if (wrapper.length > 0) {
          this.wrapperElem = wrapper[0];
          this.cusClickHandler();
        }
      });
    },
    cusClickHandler() {
      this.wrapperElem.addEventListener("click", this.hideCusBtn);
    },
    hideCusBtn(e) {
      let className = e.target.className;
      if (className === "el-icon-download") {
        let imgUrl = document.getElementsByClassName(
          "el-image-viewer__canvas"
        )[0].children[0].src;
        this.downloadImage(imgUrl);
      }
    },
    downloadImage(imgUrl) {
      let tmpArr = imgUrl.split("/");
      let fileName = tmpArr[tmpArr.length - 1];
      window.URL = window.URL || window.webkitURL;
      let xhr = new XMLHttpRequest();
      xhr.open("get", imgUrl, true);
      xhr.responseType = "blob";
      xhr.onload = function () {
        if (this.status == 200) {
          //得到一个blob对象
          let blob = this.response;
          let fileUrl = window.URL.createObjectURL(blob);
          let a = document.createElement("a");
          (document.body || document.documentElement).appendChild(a);
          a.href = fileUrl;
          if ("download" in a) {
            a.download = fileName;
          } else {
            a.setAttribute("download", fileName);
          }
          a.target = "_self";
          a.click();
          a.remove();
        }
      };
      xhr.send();
    },

;