useImage()
一个 Vue 可组合函数,返回一个用于生成优化图像 URL 的辅助函数。
有时您可能需要直接使用带有已应用转换的生成图像 URL,而不是使用 <NuxtImg> 和 <NuxtPicture> 组件。这就是 useImage() 的用武之地(以及它返回的辅助函数,您经常会看到它直接被称为 $img 或 img)。
用法
const img = useImage()
img(src, modifiers, options)
示例: 为 backgroundImage 样式生成图像 URL。
const img = useImage()
const backgroundStyles = computed(() => {
const imgUrl = img('https://github.com/nuxt.png', { width: 100 })
return { backgroundImage: `url('${imgUrl}')` }
})
img.getSizes
const img = useImage()
img.getSizes(src, { sizes, modifiers })
不稳定:
getSizes API 可能会更改或被移除。参数:
src: (字符串)原始图像 ID 的源sizes: (字符串)响应式图像尺寸列表 ({breakpoint}:{size}{unit})modifiers: (对象)传递给提供商用于调整大小和优化的修饰符width: 调整到指定的宽度(像素)height: 调整到指定的高度(像素)quality: 更改图像质量(0 到 100)format: 更改图像格式- (任何其他自定义提供商修饰符)
options: (对象)
示例: 使用 Vuetify v-img 的响应式 srcset
<template>
<v-img
:lazy-src="img(src, { width: 10, quality: 70 })"
:src="img(src, { height, quality: 70 })"
:srcset="_srcset.srcset"
:height="height"
:sizes="_srcset.sizes"
/>
</template>
<script setup lang="ts">
const props = defineProps({
height: {
type: [Number, String],
default: 500
},
src: {
type: String,
default: '/img/header-bg.jpg'
}
})
const img = useImage()
const _srcset = computed(() => {
return img.getSizes(props.src, {
sizes: 'xs:100vw sm:100vw md:100vw lg:100vw xl:100vw',
modifiers: {
format: 'webp',
quality: 70,
height: props.height
}
})
})
</script>