0

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

2 Answers 2

4

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>
Sign up to request clarification or add additional context in comments.

1 Comment

Also this method works when we want to load other assets in our script, for example using a "mp3" file in our script. We can first import it like: import testSound from "../assets/sounds/click1.mp3" and then use it like this: mouseclick.src = testSound; in some parts of our scripts.
3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.