W
W
WebDev2019-05-28 11:19:03
webpack
WebDev, 2019-05-28 11:19:03

How to display dynamic pictures from assets in vue?

The cycle creates slides that consist of a picture and a title. Pictures are stored in assets.
If it weren't for a loop, it would look like this:

<img src="@/assets/image1.jpg">
<img src="@/assets/image2.jpg">
<img src="@/assets/image3.jpg">

And in a loop like this:
<div v-for="slide in slides">
    <img :src="slide.image">
</div>

...

data() {
    return {
        slides: [
            {image: '@/assets/image1.jpg'}, 
            {image: '@/assets/image2.jpg'}, 
            {image: '@/assets/image3.jpg'}
        ]
    }
}

Here is the code that substitutes the image in src "as is", i.e. "@/assets/...".
How can I change @ to the root in this case?
Google recommends creating a getImg method:
getImg(image) {
    return require(image);
}

But firstly, require doesn't work with @ (you need to specify the path relative to the file, that is, something like '../../assets/image1.jpg'), and secondly, it doesn't look very good.
Is there a way to dynamically insert pictures via @?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Andrey Khokhlov, 2019-05-28
@andrhohlov

There are options:
https://medium.com/front-end-weekly/webpack-and-dy...
https://dev.to/pldg/lazy-load-images-with-webpack-5e80
But I would recommend you just copy such pictures in a bunch (public folder if you use vue-cli), and not import them using webpack.
Better yet, review the case. Unlimited dynamic images most likely should not be part of the application interface, but uploaded somewhere and come only as links from the server API.
The same slider - in the admin panel, the administrator uploads pictures, and the application receives data for the slider and renders.

S
skuvaWeb, 2019-05-28
@skuvaWeb

The simplest, and in my opinion the correct option is

data() {
    return {
        slides: [
            {image: require('@/assets/image1.jpg')},
        ]
    }
}

A
Alexander Drozdov, 2019-05-28
@bagzon

Pictures should be static and not touch the front in any way, I'm talking about different require and other crutches.
Only the names should be known at the front, and sucked in by the relative path (stupidly put into the img src tag), they will be automatically loaded by the browser at the specified path http: site.ru/public/image1.jpg

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question