0

I was wondering how linking an local img in vue works (dynamic). So what I do now is get the static link which will always be the same, with this src="../../../../public/groenten.png".(which works)

What I want to do is, get the image link from the prop "image". which when I console log that image prop, I get the exact same link as the static one, which is great but when I try to switch my src to: :src="this.image" then my image wont show anymore.

<template>
  <router-link v-bind:to="{ name: 'categoryPage', params: { category: this.title }  }" class="itemlink">
    <div class="category-item">
      <div class="category-item__top">
        <img
          :class="imageClassName"
          src="../../../../public/groenten.png"
          alt="category"
        />
      </div>
      <div class="category-item__bottom">
        <h3 class="category-item__title">{{ title }}</h3>
      </div>
    </div>
  </router-link>
</template>

<script>
import { defineComponent } from "vue";

export default defineComponent({
  name: "CategoryItem",
  props: {
    title: String,
    image: String,
  },
  computed: {
    imageClassName() {
      return `category-item__${this.title.toLowerCase()}`;
    }
  },
  created() {
    console.log(this.image);
  }
});
</script>
Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Kai Meyers
  • 17
  • 7
  • Does this answer your question? [Vue.js dynamic images not working](https://stackoverflow.com/questions/40491506/vue-js-dynamic-images-not-working) – kissu May 16 '22 at 16:17
  • Hi, please make a minimal effort next time (quick search with your question title). – kissu May 16 '22 at 16:17

1 Answers1

1

As far as I know, webpack is collecting static assets at compilation time. Even if at runtime the prop value is the same as the hardcoded one, it did not exist during compilation and it was not imported.

In order to import assets at runtime you have to explicitly call the require() function (webpack does the same thing during compilation):

<img :src="imageUrl" />

props: {
  image: String,
},
computed: {
  imageUrl(){
    return require(this.image)
  }
}
kissu
  • 40,416
  • 14
  • 65
  • 133
Igor Moraru
  • 7,089
  • 1
  • 12
  • 24
  • I have tried this method but it gives me a warming in my console in vs: `Critical dependency: the request of a dependency is an expression`. & this error in my browser: `Uncaught (in promise) Error: Cannot find module '../../../../public/groenten.png' at webpackEmptyContext (app.js:766:10)` – Kai Meyers May 16 '22 at 18:48