vue/cli renaming images unable to access

Viewed 193

I can easily add an image on any component like this: <img src="@/images/q3.png"> but when I see the devtools the src has a different name <img src="/img/q3.91066fb2.png">. The vue/cli adds the image to a diferent folder and it adds a random number to the name. The problem is that I need to use the image inside a v-html as a text: v-html='<img src="@/images/q3.png">'(the text is inside a variable in data, this is just a simplification) but this doesn't work showing a blanck image. What can I do to access this image?

Ps: I have multiple images, I need a solution that works with all of them

Edit: I find this possible duplicate: vuejs v-html image tag not resolving src. It helps me see that the problem is the path. So I changed the images folder to be alongside the src and public folders and i changed the path to <img src="images/q3.png"> and it worked. Though I don't know if this is best practice, could not make the images folder inside the public or src folders.

Edit: As suggested I can just move the images folder into the public folder while remain with the same path images/q3.png

1 Answers

I'm thinking you could create a method that would load the image content (not path) and place that directly into the dynamic HTML. Something like so:

new Vue({
    methods: {
        generateImg(path) {
            let img = require(path);
            return '<img src="' + img + '">'
        }
    }
}

So you'd call generateImg("@/images/q3.png") and place the returned value in your v-html. You can reuse this for other images.

I haven't tested this, but would it work for you?

--

Alternatively, if you place the images in the public directory, you should be able to access them without require.

So let's say all the images are in public/images. Now the path to q3.png will be yoursite.com/images/q3.png, as the files in public are not dynamically generated (so there will be no random number like 91066fb2 that vue adds to it), but you can just use images/q3.png within your code.

More here: https://stackoverflow.com/a/53628289

Related