2
votes

How do I reference an image in the Setup function in the Composition API? The path is '../assets/pic.png'

If I use the path directly inside the template, as the src in an img tag, the image displays on the page. When I inspect it, it shows the image name, followed by an id, then the file extension e.g: “/img/pic.123456.png”. I can do it like this to get what I want, but it doesn’t seem like the correct way of doing things in Vue.

I’m thinking it should be something like:

<template>
    <div>
        <img src="pic">
    </div>
</template>


<script>

import { ref } from 'vue'
export default {

    setup(){

        const pic = ref('../assets/pic.png')

        return  { pic }
    }  

}

</script>

<style>

</style>

I believe it would work like this in the Options API (without ‘ref’, of course). I can’t get it to work with the Composition API. I'm thinking it may be something to do with the 'id'. Also how would I reference images in an array?

Thanks.

2
to reference images in an array, you will regularly use a combination of v-for. You can read about using referencing an array in the v-for in the docs.wittgenstein

2 Answers

0
votes

have you tried to use template refs?

<template>
  <img ref="pic" :src="picUrl" />
</template>

<script>
import { ref, onMounted } from 'vue'

export default {
  setup() {
    const pic = ref(null)
    const picUrl = ref('https://v3.vuejs.org/logo.png')

    onMounted(() => {
      console.log(pic.value) // <img src="https://v3.vuejs.org/logo.png">
    })

    return {
      pic,
      picUrl
    }
  }
}

after the mounted hook the console log will reference the image item.

0
votes

You need to require the image first with the require function, and then pass the returned value to ref. and you should bind the src attribute with v-bind.

here is a complete example based on your code:

<template>
    <div>
        <img v-bind:src="pic">
    </div>
</template>


<script>

import { ref } from 'vue'
export default {

    setup(){

        const pic = ref(require('../assets/pic.png'))

        return  { pic }
    }  

}

</script>

<style>

</style>