How to import and use image in a Vue single file component?

aks picture aks · Jul 15, 2017 · Viewed 111.8k times · Source

I think this should be simple, but I am facing some trouble on how to import and use an image in Vue single file component. Can someone help me how to do this? Here is my code snippet:

<template lang="html">
    <img src="zapierLogo" />
</template>
    
<script>
    import zapierLogo from 'images/zapier_logo.svg'
    
    export default {
    }
</script>
    
<style lang="css">
</style>

I have tried using :src, src="{{ zapierLogo }}", etc. But nothing seems to work. I was not able to find any example too. Any help?

Answer

papey picture papey · Jul 15, 2017

As simple as:

<template>
    <div id="app">
        <img src="./assets/logo.png">
    </div>
</template>
    
<script>
    export default {
    }
</script>
    
<style lang="css">
</style> 

Taken from the project generated by vue cli.

If you want to use your image as a module, do not forget to bind data to your Vuejs component:

<template>
    <div id="app">
        <img :src="image"/>
    </div>
</template>
    
<script>
    import image from "./assets/logo.png"
    
    export default {
        data: function () {
            return {
                image: image
            }
        }
    }
</script>
    
<style lang="css">
</style>

And a shorter version:

<template>
    <div id="app">
        <img :src="require('./assets/logo.png')"/>
    </div>
</template>
    
<script>
    export default {
    }
</script>
    
<style lang="css">
</style>