簡體   English   中英

如何正確銷毀cropper.js,以便下一次裁剪將獲得新圖像?

[英]how to destroy cropper.js properly so that next crop will get new image?

我有一個 vue 應用程序表單,其中包含一個通過 ant-design-vue 上傳的圖像上傳器。 我將此圖像上傳器鏈接到一個新組件,該組件使用cropper.js 在上傳后處理圖像以進行裁剪。 第一次作物一切都很好,工作完美。 但是當用戶需要第二次更換照片並再次裁剪時,裁剪區域上的圖像仍然使用第一張圖像。 第三次上傳將裁剪第二個區域,下一次將收到相同的影響。

這是我的代碼的結構:

<template>
  <div>
    <a-row :gutter="16">
      <img ref="image" :src="initialImage">
    </a-row><br />
    <a-row :gutter="16">
      <a-button type="primary" style="float: right;" @click="crop">Crop</a-button>
      <a-button style="float: right; margin-right: 5px;" @click="cancel">Cancel</a-button>
    </a-row>
  </div>
</template>

這是腳本和樣式:

<script>
import Cropper from 'cropperjs';

export default {
  name: 'PostCropper',
  props: {
    uploadedImage: String,
  },
  data() {
    return {
      cropper: {},
      updatedImage: {},
      initialImage: this.uploadedImage,
    };
  },
  methods: {
    crop() {
      this.$emit('update-image', this.updatedImage);
    },
    cancel() {
      this.$emit('cancel-upload');
    },
    cropImage() {
      this.cropper = new Cropper(this.$refs.image, {
        autoCropArea: 1,
        cropBoxResizable: false,
        zoomOnTouch: true,
        zoomable: true,
        scalable: false,
        aspectRatio: 1,
        resizable: false,
        crop: () => {
          const canvas = this.cropper.getCroppedCanvas();
          this.updatedImage = canvas.toDataURL('image/png');
        },
      });
    },
  },
  watch: {
    uploadedImage() {
      this.cropper.destroy();
      this.initialImage = this.uploadedImage;
      this.cropImage();
    },
  },
  mounted() {
    this.cropImage();
  },
};
</script>

<style lang="scss">

.cropper-crop-box .cropper-view-box {
    border-radius:50%;
  }
</style>

問題發生在這里:

          this.cropper = new Cropper(this.$refs.image, {
            autoCropArea: 1,
            cropBoxResizable: false,
            zoomOnTouch: true,
            zoomable: true,
            scalable: false,
            aspectRatio: 1,
            resizable: false,
            crop: () => {
              const canvas = this.cropper.getCroppedCanvas();
              this.updatedImage = canvas.toDataURL('image/png');
            },
          });

我已經破壞了 this.cropper 但仍然裁剪了相同的圖像。 我試圖通過 console.log 預覽 this.cropper、this.image、this.initialImage、this.uploadedImage 的每個值,但它們都沒有問題。 它將在 this.uploadedImage 上攜帶新值通過使用 vue watch 進行更改。 我不知道為什么只有上面的這個函數仍然帶有相同的圖像。 有什么方法可以初始化 this.cropper 或者可以解決我的問題的方法,例如重新渲染這個子組件?

您可以通過給它們一個鍵並更新鍵來刷新 Vue 元素。 例如,您在何處導入 PostCropper 組件:

<PostCropper v-bind:key="refreshValue" />

然后在父元素的數據屬性中分配一個名為refreshValue的屬性,並給它一個類似 1 的值。然后當您需要刷新組件時,您只需更改該值。 這可能需要您從PostCropper組件向父組件發出一個事件,然后遞增refreshValue

我有另一種方法來銷毀父組件中的子組件而不是銷毀變量。 通過使用 v-if 方法銷毀導入的組件,它完美地工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM