How to reference static image assets in Vue JS
Learn how to reference images from assets folder in Vue template using Webpack's require() method or using the relative path.
In this article, we will learn how to reference static image assets in Vue JS.
Let's say we want to use an image that is saved locally in our assets folder in Vue project.
To use it with an < img > tags we can reference the image in two ways:
Using the relative path in Vue template
If you want to use it directly in Vue template we can do it like this.
<img alt="Vue logo" src="./assets/photo.jpeg" width="80%" />
We have directly used the image from the assets folder in our vue template.
Here we are using the relative path "./assets/photo.jpeg" , it will get replaced by an auto-generated URL based on the Webpack output configuration.
Using require() to get image asset path
To get the assets path using JavaScript we use the require() in Vue. This leverages the Webpack's module and the file is processed by the file-loader and returns us the resolved URL.
<template> <div id="app"> <img :src="img" width="80%" /> </div> </template> <script> export default { name: "App", data() { return { img: require("./assets/photo.jpeg"), }; }, }; </script>
Here, we have used require() to reference the image in our data property, and using v-bind ( :src) we have bind it to the < img > tag src attribute.
We can also use require() directly in our template but we have to bind it to the src attribute like this
<img alt="Vue logo" :src="require('./assets/photo.jpeg')" width="80%" />
DEMO:

Related Posts
Easy Way to use localStorage with Vue
Short article on how to use local storage with Vue and learn saving and storing data in local storage with the setItem() and getItem() methods.
Force update Vue to Reload/Rerender component
Short tutorial on how to correctly force update Vue.js component to reload or rerender. The component is reinitialized without having to do a browser refresh.
Set and get cookies in a browser in Vue App
Find out how to set and get cookies in a browser for your webpage in Vue using vue-cookies package.
Save vuex state after page refresh in Vue App
Short tutorial on how to save (or persist) data in a vue application using Vuex and vuex-persist npm package.
