How do I reference an image inside the Setup function in the Composition API in Vue 3?

Viewed 2088

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 Answers

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>

I had the same issue, and using require didnt work for me, finally, I got this:

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


<script>

import pic from '../assets/pic.png'
export default {

    setup(){
    }  

}

</script>
Related