创建imghook.js:
//首先图片是1:1比例,解决不同图片免去单独设置宽高
// 在函数里创建ref,可以避免多张图片使用造成取值的问题
import { ref } from "vue"
// 使用解构视图是不会重新渲染的
const getSize = (naturalWidth, naturalHeight,imgWidth,imgHeight,imgStyle) => {
const clientWidth = document.documentElement.clientWidth
const fontSize = clientWidth / 750
imgWidth.value = naturalWidth * fontSize + "px"
imgHeight.value = naturalHeight * fontSize + "px"
imgStyle.value = { width: imgWidth.value, height: imgHeight.value }
}
export const imgHook = (e) => {
let imgStyle = ref({})
const imgWidth = ref("")
const imgHeight = ref("")
const { naturalWidth, naturalHeight } = e // 可以直接从dom对象拿这两个属性
getSize(naturalWidth, naturalHeight,imgWidth,imgHeight,imgStyle)
imgStyle.value = { width: imgWidth.value, height: imgHeight.value }
// 监听屏幕变化事件重新加载 可不用,浏览器测试时候频繁切换屏幕就加了。。。。。。
window.addEventListener("resize", () => {
getSize(naturalWidth, naturalHeight,imgWidth,imgHeight,imgStyle)
})
return imgStyle
}
index.html:
<img ref="prizeImgRef" class="img" :style="imgStyle.value" @load="imgLoad($event)" src="../assets/k2.png" alt="" srcset="">
import {imgHook} from '@/hooks/imgHook.js' // 使用hook值得时候不要.value。会丢失响应式
let imgStyle = ref({})
let prizeImgRef = ref(null)
const imgLoad =(e)=> {
// dom对象传过去
imgStyle.value=imgHook(prizeImgRef.value)
}
demo文件地址https://github.com/cc147151/luck