Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass dynamic image url in nuxt project

I want to pass image url to child component but image is not showing.

I tried v-attr, :attr, :src properties.

pages/index.vue

<ThumbNail img-url="assets/img/igsim_intro.png"/>

components/Thumbnail.vue

<!-- Failed to resolve directive: attr -->
<img v-attr="imgUrl" /> 

<!-- 404 Not found: http://localhost:3000/assets/img/pds_main.png -->
<img :src="imgUrl" />

<img :attr="{src: imgUrl}" /> 
<script>
export default {
  name: "ThumbNail",
  props: {
    imgUrl: {
      type: String,
      default: ''
    }
  }
}
</script>

I expect Thumbnail.vue show images as passed url.

like image 872
SooJungChae Avatar asked Jun 25 '19 07:06

SooJungChae


2 Answers

As the src properties will be replaced by Webpack, you could do require function like this

ChildComponentExample.vue

<templae>
  <div>
    <img :src="imageUrl">
  </div>
</template>

<script>
export default {
  props: {
    imageUrl: {
      type: String,
      default: ''
    }
  }
}
</script>

ParentComponent.vue

<template>
  <ChildComponentExample :image-url="require('~/assets/myimage.png')" />
</template>
like image 96
Aditya Kresna Permana Avatar answered Sep 28 '22 05:09

Aditya Kresna Permana


From this answer by Aditya Kresna Permana

For me, It's not working correctly because :image-url in ParentComponent.vue not the same as props in ChildComponentExample.vue

:image-url="require('~/assets/myimage.png')" change :image-url to :imageUrl (same as in props in ChildComponentExample.vue )

Result: :imageUrl="require('~/assets/myimage.png')"

Example ParentComponent.vue:

<template>
  <div v-for="item in items" :key="item.id>
    <ChildComponent 
      :imageURL="require(`~/assets/${item.imgURL}`)" 
      :title="item.title"
      :descriptions="item.descriptions"
    />
  </div>
</template>

<script>
import ChildComponent from '~/components/ChildComponentExample.vue'

export default {
components:{
  ChildComponent,
},
data() {
    return {
      items: [
        {
          id: 1,
          imgURL: '01-1.webp',
          title: 'Title1',
          descriptions: 'Lorem ipsum',
        },
        {
          id: 2,
          imgURL: '02-1.webp',
          title: 'Title2',
          descriptions: 'Lorem ipsum',
        },
      ],
    }
  }
} 
</script>

Example ChildComponentExample.vue:

<template>
  <div>
    <div>
      <img :src="imageURL" alt="Alt text" />
      <div>
        <h3> {{ title }} </h3>
        <div> {{ descriptions }} </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    imageURL: {
      type: String,
      required: true,
      default: '',
    },
    title: {
      type: String,
      required: true,
      default: 'Title',
    },
    descriptions: {
      type: String,
      required: true,
      default: 'No descriptions',
    },
  },
}
</script>
like image 31
l2D Avatar answered Sep 28 '22 06:09

l2D