Sean Liu
Sean Liu

Reputation: 1803

How to display image url in vue.js

So This is correct way to display image in vue

<img class="cur-img"  src="~@/assets/img/test.png" alt="temp-img">

However, the following way is incorrect, if templateImg is a string represent by "~@/assets/img/test.png"

            <div v-for="(item,index) in items" :key="index">
                   <img  :src="item.templateImg" alt="template-img">
            </div>

Is there any way to fix it?

enter image description here

Upvotes: 0

Views: 7763

Answers (2)

Beshambher Chaukhwan
Beshambher Chaukhwan

Reputation: 1448

Use the following:

<img :src="require(item.templateImg)">

When we are binding src to a variable, it is giving its raw value to the img tag, which means it's expecting a full resource URL. It's up to us to provide a complete data URL to that resource, which means creating a corresponding absolute resource URL out of the relative asset path that we're using.

Thus, we need to fetch it using require(). If you are using an absolute path like a base64 data image URL, or compete image URLs, then in such cases you don't need require(), and your current code will work just fine.

Upvotes: 3

nVitius
nVitius

Reputation: 2214

Usually, you will want to import the asset in your JS code. For example:

<template>
  <img :src="image" />
</template>

<script>
  import testImage from "@/assets/img/test.png"

  export default {
    image: testImage
  }
</script>

Upvotes: 4

Related Questions