How to import and use image in a Vue single file c

2019-01-25 03:50发布

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?

2条回答
放我归山
2楼-- · 2019-01-25 04:33

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> 
查看更多
等我变得足够好
3楼-- · 2019-01-25 04:40

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.

查看更多
登录 后发表回答