How to preview image in element ui?

2.4k Views Asked by At

I am using element ui el-image. And I want to preview my image when clicked with (:preview-src-list). But When I click first time it doesnt preview anything. just add's my downloaded image. So I need to click 2 times. But I want to click 1 time.

Here is my template code:

<el-image :src="src"
          :preview-src-list="srcList"
          @click="imgClick"></el-image>

ts code:

src = null;
srcList = [];

product = 'shoe1';

imgClick() {
  prevImg(product).then(resp => {
    const url = window.URL.createObjectURL(new Blob([resp.data]));
    this.srclist = [url];
  });
}

@Watch("product")
changed(value) {
  getProductImage(value).then(resp => {
    const url = window.URL.createObjectURL(new Blob([resp.data]));
    this.src = url;
  }).catc(e => {
    alert(e);
  });
}

mounted() {
  this.changed(product);
}
1

There are 1 best solutions below

0
On BEST ANSWER

I think these things happen because when you click on that image it will trigger clickHandler:

...
  clickHandler() {
    // don't show viewer when preview is false
    if (!this.preview) {
      return;
    }
    ...
  }
...

From source

And the preview is the computed property:

...
  preview() {
    const { previewSrcList } = this;
    return Array.isArray(previewSrcList) && previewSrcList.length > 0;
  }
...

From source

So nothing happened in the first click but after that you set preview-src-list and click it again then it works.

If you code is synchronous you can use event like mousedown which will trigger before click event.

<el-image
  :src="url"
  :preview-src-list="srcList"
  @mousedown="loadImages">
</el-image>

Example

But if you code is asynchronous you can use refs and call clickHandler after that.

...
  // fetch something
  this.$nextTick(() => {
    this.$refs.elImage.clickHandler()
  })
...

Example