繁体   English   中英

获取图像宽度和高度在 50% 的时间在 vue js 中工作

[英]Get image width and height working 50% of the time in vue js

我在视图文件中有这个结构,在 Vue js 中:

<template>
    <div class="myImageData">
       {{ imageCrop(whateverImageUrl) }}
    </div>
<template>

<script>
 export default {
     methods: {
         imageCrop: function(iiif) { 
           let image = new Image();
           image.src = iiif; 
           let width =  image.width; 
           let height = image.height;
           return image.src + " this is width " + width + " and this is height " + height
         }
     }
}

有时我得到正确的高度和宽度,但有时我得到 0 和 0。是否有一些缓存问题? 方法是正确的方法吗? 我是 Vue 的新手,所以我不太了解它是如何工作的。

编辑:如果我使用

 image.onload = () => {
       let height = image.height;
       let width = image.width;
       return image.src + " this is width " + width + " and this is height " + height
 }

页面上没有任何内容。 我试图进行这样的错误处理:

nameError: function(){
        try {
            const error = new Error();
            return error.message;
        } catch (ex) {
            return ex.message;
        }

它在 DOM 中生成一个带有 this 的事件:

const invoker = (e) => { // 异步边缘情况 #6566:内部点击事件触发补丁,事件处理程序 // 在补丁期间附加到外部元素,并再次触发。 // 发生这种情况是因为浏览器在事件传播之间触发了微任务滴答。 // 解决方案很简单:我们在附加处理程序时保存时间戳, // 只有当传递给它的事件被触发时,处理程序才会触发 // 在它被附加之后。 const timeStamp = e.timeStamp || _getNow(); if (skipTimestampCheck || timeStamp >= invoker.attached - 1) { callWithAsyncErrorHandling(patchStopImmediatePropagation(e, invoker.value), instance, 5 /* NATIVE_EVENT_HANDLER */, [e]); }

您可能需要等到图像完全加载

let img = new Image();
image.src = iiif;
let text = "";
img.onload = () => {
  let width =  image.width; 
  let height = image.height;
  text image.src + " this is width " + width + " and this is height " + height
}
return text;

您可能需要使此函数 async await 不立即返回空字符串

正如@theshark 在评论中指出的那样,创建图像以检索其尺寸是一个异步过程。 AFAIK,您将无法在渲染中使用这种方法的结果。

目前尚不清楚您要实现的目标是什么,但最简单的方法是在您的imageCrop方法获得尺寸后将尺寸存储在组件的数据中。 这个方法不必在模板中调用,而是在created钩子中调用。

您可以直接在模板中绑定组件的数据:

<template>
    <div class="myImageData">
       {{ src }} this is width {{ width }} and this is height {{ height }}
    </div>
</template>

<script>
 export default {
    data() {
      return {
        src: "",
        width: 0,
        height: 0
      }
    },
    created() {
      this.imageCrop(whateverImageUrl);
    },
    methods: {
      imageCrop: function(iiif) {
        let image = new Image();
        image.onload = (event) => {
          this.width = event.target.width;
          this.height = event.target.height;
          this.src = event.target.src;
        }
        image.src = iiif; 
      }
    }
}
</script>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM