Is there a way to handle varying image widths in Nuxt without compromising the layout? I have an image component that needs to adjust for different screen sizes, and I want the title and description to always match the width of the image. Here's what I currently have:
<div>
<h2 >{{insightsImage.title}}</h3>
<img :src='ifMobile ? mobileImage.url : image.url' />
<p>some text</p>
</div>
I'm looking for a more efficient solution, possibly using just CSS, but so far none have worked with variable image widths.
This is my current workaround:
<div>
<h2 :style='`max-width: ${imageSize}`'>{{insightsImage.title}}</h3>
<img :src='ifMobile ? mobileImage.url : image.url' />
<p :style='`max-width: ${imageSize}`'/>some text</p>
</div>
export default defineComponent({
computed: {
imageSize(): string {
if (!process.browser) return ''
const image = new Image();
image.src = this.image.url;
return `${image.width > 0 ? image.width : 800}px`
}
I've explored various solutions, but haven't found a perfect one yet. Any recommendations on how to approach this?
I considered using refs like this: Using $refs in a computed property
However, the official docs advise against abusing refs in computed props. Plus, the computed width doesn't update when the image source changes. Any other ideas?