13

I am referencing an image url in a vue component like

<img alt="Vue logo" src="~statics/reports/logo.png">

this works

but while trying

<img alt="Vue logo" :src="getURL()">


data() {
    return { imgPath: "~statics/reports/logo.png" };
  },

  methods: {

    getURL() {
        // 

      // console.log(path)
      return (this.imgPath)
    }
  },

it fails

My folder structure is enter image description here

In the first case the path is resolved to

http://localhost:8081/img/logo.82b9c7a5.png

and served automatically by the dev server

The path is not resolved in the second case it remains http://localhost:8081/~statics/reports/logo.png

I am using vue cli 3 generated default config for webpack .

I do not want to use relative paths for all images like ../images/ as it makes it more verbose. I have tried require(pathVariable) that too does not work Please help with resolving the img path when the url is dynamic ie asset name comes from server and i append a path in a method or computed and use :src dynamicbinding to serve it

Sainath S.R
  • 3,074
  • 9
  • 41
  • 72

2 Answers2

28

The second way fails because "~" try to get this asset from node_modules. You can read more about handling assets here: https://cli.vuejs.org/guide/html-and-static-assets.html#relative-path-imports.

To fix it just use require like below:

data() {
  return {
    imgPath: require('@/statics/logo.png')
  }
}

..or directly in template:

<img alt="Vue logo" :src="require('@/statics/logo.png')">
achwilko
  • 774
  • 5
  • 7
  • 1
    I get `Uncaught (in promise) ReferenceError: require is not defined`. Do I need to configure something first in order to make this work? – Fred Jan 28 '23 at 13:49
  • 1
    If you are using `Vite` then require won't work @Fred – Piyush Singhania Feb 03 '23 at 06:24
  • Ah, I got confused about `Vue 3` and `vue-cli 3` (which creates `Vue 2` code) again. Thanks for the heads up! – Fred Feb 03 '23 at 11:39
0

For Vue 3 projects you can use the following:

<img src="./assets/logo.png" />
Abeyance
  • 133
  • 1
  • 2
  • 7