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

被刻印的时光 ゝ 提交于 2019-11-26 07:43:13

问题


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 nothings seems to work. was not able to find any example too. Any help?


回答1:


As simple as :

<template>
  <div id="app">
    <img src="./assets/logo.png">
  </div>
</template>

<script>
export default {
}
</script>

<style lang="scss">
</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="scss">
</style> 

And a shorter version :

<template>
  <div id="app">
    <img :src="require('./assets/logo.png')" />
  </div>
</template>

<script>
export default {
}
</script>

<style lang="scss">
</style> 



回答2:


It is heavily suggested to make use of webpack when importing pictures from assets and in general for optimisation and pathing purposes

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">




回答3:


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="">



回答4:


These both work for me in JavaScript and TypeScript

<img src="@/assets/images/logo.png" alt=""> 

or

 <img src="./assets/images/logo.png" alt="">


来源:https://stackoverflow.com/questions/45116796/how-to-import-and-use-image-in-a-vue-single-file-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!