DaveIdito
DaveIdito

Reputation: 1606

Why does javascript expression in Vue binding <g-image> does not work?

I have a use case where I have to bind the src attribute of the <g-image> tags dynamically. I have learned that I can use javascrpt expressions in v-bind, so I proceeded on. But here's the paradox:

<g-image :src="'~/images/blocks.png'" width="500"/> // does not work
<g-image src="~/images/blocks.png" width="500"/> //works!

Why does one work and the other does not, even though, they shoud evaluate to the same values? I am planning to then use it as <g-image :src="'~/images/'+imageName+'.png'" width="500"/>

Upvotes: 0

Views: 324

Answers (1)

Michal Lev&#253;
Michal Lev&#253;

Reputation: 37903

Gridsome documentation

The src attribute and options like width, height and quality must be static values because they are compiled into an object which contains URLs and other information that will be rendered into an img tag

I admit Im not a regular Gridsome user and everything which follows comes from my understanding of Vue/Webpack, Gridsome docs and this issue

g-image is component provided by Gridsome intended to make use of responsive images easier. Most of the job is done during build time - they use some Webpack magic to process Vue templates. If g-image is found, it's src attribute is read and if it contains path to existing local image, they take the image, generate multiple copies of it with different sizes and add srcset attribute which allows the browser to decide which image to download depending on screen size...

Important thing is this is all happening at build time. It means your app is not running which means it is not possible to evaluate any JS dynamic expression used for src (probably based on app state)!

It may seem as using require() (which is Webpack construct which allows some dynamic content) makes it work but you will loose main g-image feature which is automatic generation of responsive image...

This is not an issue easy to solve on Gridsome side (look how old the issue is and how much attention from maintainers it gets). If you really want dynamic responsive images, you will need to use simple img and generate image variants (and srcset) some other way. Or you can use Cloudinary to generate those images on the fly....

Upvotes: 0

Related Questions