Search code examples
vue.jsvuejs2vue-cli-3

vue-cli3 public folder img doesn't show up


Does anyone know how to use the src attribute with an img file in a vue project's public folder? The browser is not finding the image.

I'm using Vue CLI 3.7.0

▼ folders

 |
 +-- src
 |    
 +-- public
       |  
       +-- favicon.ico
       +-- logo.png
       +-- index.html

I've tried something like :src="xxx", but that didn't work.

<template>
    <div>
        <img :src="'/favicon.ico'">
        <img :src="`${publicPath}favicon.ico`">
     </div>
</template>

<script>
    export default {
        data: function() {
            return {
                publicPath: process.env.BASE_URL
            };
        }
    }
</script>

Solution

  • Update

    From the comments below, it seems you're running

    vue serve
    

    Only a Vue CLI project knows about the public directory and process.env.BASE_URL. You need to run your project instead of using the instant prototyping of vue serve.

    In other words, run

    npm run serve
    

    See https://cli.vuejs.org/guide/cli-service.html#using-the-binary


    If you have a file structure like this

    ├── public
    │   ├── favicon.html
    │   ├── index.html
    │   ├── logo.png
    

    then your code to display logo.png should look like

    <template>
      <div>
        <img :src="`${publicPath}logo.png`">
      </div>
    </template>
    
    <script>
    export default {
      data () {
        return {
          publicPath: process.env.BASE_URL
        }
      }
    }
    </script>
    

    See https://cli.vuejs.org/guide/html-and-static-assets.html#the-public-folder


    If you have your image in

    ├── public
    │   ├── img
    │   │   ├── logo.png
    

    then your component template code becomes

    <img :src="`${publicPath}img/logo.png`">