Search code examples
vue.js

Vue fallback to asset images


I have a bunch of entities I want to display on a page in a Vue 3 application. Each entity should have an image URL. If an entity does not have such a URL, I want to display a default image that's stored in /src/assets/images/default.png

So I've created a computed property that returns the image URL, either entity.url or the URL above.

Unfortunately, this doesn't work, instead of getting the default image I'm getting no image, and the Vue dev webserver returns index.html. This is because Vue's handling of static assets doesn't work when the static asset URL is returned in runtime.

The image is shown properly if I hard-code the URL @/assets/images/default.png, but not if I return this as a string (dropping the @ makes no difference).

How can I make Vue handle static assets that are referenced dynamically?


Solution

  • I'd use v-if/v-else to show the appropriate image based on whether entity.url exists ..

    <img v-if="entity.url" :src="entity.url" />
    <img v-else src="@/assets/images/default.png" />