Vue中如何根据屏幕尺寸条件渲染不同的img src?
Vue根据设备尺寸切换图片src的实现方案
下面提供三种实用的实现方式,根据你的项目需求选择即可:
1. 原生picture元素(无需JS,推荐静态场景)
利用HTML原生的<picture>标签,浏览器会自动根据媒体查询匹配并加载对应图片,性能最优且语义化:
<template> <picture> <!-- 桌面端图片(匹配md断点,这里假设md为768px) --> <source media="(min-width: 768px)" srcset="/path/to/desktop-image.jpg"> <!-- 移动端默认图片 --> <img class="absolute z-10 inset-x-0 top-0 w-full object-cover max-h-60 md:h-60" src="/path/to/mobile-image.jpg" alt="图片描述文本" > </picture> </template>
2. Vue响应式变量+窗口监听(纯Vue实现)
通过监听窗口尺寸变化,动态更新图片地址,适合需要结合其他Vue状态的场景:
<script setup> import { ref, onMounted, onUnmounted } from 'vue' import Main from "./components/Main.vue"; const imgSrc = ref('/path/to/mobile-image.jpg') let resizeObserver = null // 初始化判断图片地址 const updateImageSrc = (width) => { imgSrc.value = width >= 768 ? '/path/to/desktop-image.jpg' : '/path/to/mobile-image.jpg' } onMounted(() => { updateImageSrc(window.innerWidth) // 使用ResizeObserver监听窗口尺寸变化 resizeObserver = new ResizeObserver(entries => { updateImageSrc(entries[0].contentRect.width) }) resizeObserver.observe(document.documentElement) }) onUnmounted(() => { resizeObserver?.disconnect() }) </script> <template> <img class="absolute z-10 inset-x-0 top-0 w-full object-cover max-h-60 md:h-60" :src="imgSrc" alt="图片描述文本" /> </template>
3. 借助VueUse简化代码(适合已引入VueUse的项目)
如果你的项目已经使用了VueUse工具库,可以用useWindowSize快速实现:
<script setup> import { useWindowSize } from '@vueuse/core' import { computed } from 'vue' import Main from "./components/Main.vue"; const { width } = useWindowSize() const imgSrc = computed(() => { return width.value >= 768 ? '/path/to/desktop-image.jpg' : '/path/to/mobile-image.jpg' }) </script> <template> <img class="absolute z-10 inset-x-0 top-0 w-full object-cover max-h-60 md:h-60" :src="imgSrc" alt="图片描述文本" /> </template>
选择建议
- 静态场景优先用
<picture>标签,无需JS介入,更高效。 - 需要结合Vue内部状态逻辑时,选择响应式变量监听或VueUse方案。
内容的提问来源于stack exchange,提问作者Ninety9Balloons
相关产品推荐
相关产品推荐

