一般情况下在 vue 中处理 img 元素的 load 事件可使用下以下写法(Chrome中可用)
<template>
<img src="demo.png" @load="onImageLoad">
</template>
<script setup>
const onImageLoad = (event) => {
const width = event.path[0].width;
const height = event.path[0].height;
}
</script>
在Safari中以上写法不生效,需要使用以下写法(同时兼容 Chrome 和 Safari )
<template>
<img src="demo.png" id="image">
</template>
<script setup>
const image = document.getElementById("image");
image.addEventListener("load", () => {
// chrome 浏览器中获取宽高
if (event.path) {
const width = event.path[0].width;
const height = event.path[0].height;
// safari 浏览器中获取宽高
} else {
const width = event.target.width;
const height = event.target.height;
}
}, false);