0

I'm making an app with vue and ionic, but when trying to load assets the paths are not resolving.

<template>
    <div id="index">

        <img :src="image.src" v-for="image in images">

    </div>
</template>

<script>
export default {

    name: 'Inicio',

    data() {
        return {
            images: [
                {src: '@/assets/xxx.png'},
                {src: '@/assets/xxxx.png'},
                {src: '@/assets/xxx.png'}
            ]
        }
    }
}
</script>

The path in the src attribute appears like the one typed in the var '@/assets/xxx.png'.

But if I do it directly, by typing the src in the image manually, like <img src="@/assets/xxx.png"> It loads the image correctly.

  • Can you provide the webpack configuration (or the command you used to scaffold your VueJS project) ? – Cédric M. Apr 26 '19 at 08:43
  • Possible duplicate of [Vue.js image v-for bind](https://stackoverflow.com/questions/44948916/vue-js-image-v-for-bind) – A. Larsson Apr 26 '19 at 08:47
  • Maybe you can find your answer here https://stackoverflow.com/questions/44948916/vue-js-image-v-for-bind – A. Larsson Apr 26 '19 at 08:47
  • My answer in this question might help you out: https://stackoverflow.com/questions/55818228/how-to-dynamically-bind-img-using-props/55826613#55826613 – Adam Orłowski Apr 26 '19 at 08:48
  • The question is not a duplicate of the one provided, as the problem isnt vue not binding the src, the problem is webpack not resolving the path provided by the src attribute when its supplied by a variable. @Stilleur I haven't changed the webpack configuration, its the default one provided by a fresh installation of Vue using vue cli 3 UI. – Francisco Garrido Apr 26 '19 at 08:52

1 Answers1

2

You cannot refer static assets using v-for, since webpack needs to rewrite static paths before runtime. The values of image.src will only be read and parsed to template at runtime, so there is no compiling from webpack to translate relative paths to real paths in bundle.

One solution is using require():

<template>
    <div id="index">

        <img :src="image.src" v-for="image in images">

    </div>
</template>

<script>
export default {

    name: 'Inicio',

    data() {
        return {
            images: [
                {src: require('@/assets/xxx.png') },
                {src: require('@/assets/xxxx.png') },
                {src: require('@/assets/xxx.png') }
            ]
        }
    }
}
</script>

Demo sandbox: https://codesandbox.io/s/811px8kn88

blaz
  • 3,981
  • 22
  • 37