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?
You can also use the root shortcut like so
<template>
<div class="container">
<h1>Recipes</h1>
<img src="@/assets/burger.jpg" />
</div>
</template>
Although this was Nuxt, it should be same with Vue CLI.
I encounter a problem in quasar
which is a mobile framework based vue
, the tidle syntax ~assets/cover.jpg
works in normal component, but not in my dynamic defined component, that is defined by
let c=Vue.component('compName',{...})
finally this work:
computed: {
coverUri() {
return require('../assets/cover.jpg');
}
}
<q-img class="coverImg" :src="coverUri" :height="uiBook.coverHeight" spinner-color="white"/>
according to the explain at https://quasar.dev/quasar-cli/handling-assets
In *.vue components, all your templates and CSS are parsed by vue-html-loader and css-loader to look for asset URLs. For example, in <img src="./logo.png"> and background: url(./logo.png), "./logo.png" is a relative asset path and will be resolved by Webpack as a module dependency.
I came across this issue recently, and i'm using Typescript. If you're using Typescript like I am, then you need to import assets like so:
<img src="@/assets/images/logo.png" alt="">
These both work for me in JavaScript and TypeScript
<img src="@/assets/images/logo.png" alt="">
or
<img src="./assets/images/logo.png" alt="">
If you wish to load them by webpack you can simply use :src='require('path/to/file')'
Make sure you use :
otherwise it won't execute the require statement as Javascript.
In typescript you can do almost the exact same operation: :src="require('@/assets/image.png')"
Why the following is generally considered bad practice:
<template>
<div id="app">
<img src="./assets/logo.png">
</div>
</template>
<script>
export default {
}
</script>
<style lang="scss">
</style>
When building using the Vue cli, webpack is not able to ensure that the assets file will maintain a structure that follows the relative importing. This is due to webpack trying to optimize and chunk items appearing inside of the assets folder. If you wish to use a relative import you should do so from within the static
folder and use: <img src="./static/logo.png">
Source: Stackoverflow.com