Why Vue can't resolve image from localhost?

Viewed 4619

As a back-end for vue.js I use laravel (port 8000)

In my db I have the user and the name of it's profile photo (this.user.photo).

So, I want to show this photo.

<img :src="require(`http://localhost:8000/images/${this.user.photo}`)" alt="Profile Photo">

When I go to http://localhost:8000/images/1.png I actually see the image, but the Vue says:

Module not found: Error: Can't resolve 'http://localhost:8000'

PS: console.log(this.user.photo) outputs 1.png

UPD: I've seen many solutions, like this or this, but they do not work

4 Answers

Looks like your images are already hosted on the server and you are not bundling them during build. In this case, you need not use require and directly refer to your images in the template as

<img :src="'http://localhost:8000/images/' + user.photo" alt="Profile Photo">

Remember that require is a method provided by webpack to resolve your dependancy URLs during build such that you need not worry about the absolute URLs. require helps us refer to URLs relative to the modules which are resolved by webpack during build.

In short, use require when you have static assets inside your Vue project module

You can call the image directly with path if the image is not in public path

 <img :src=`../../images/${user.photo}` alt="Profile Photo">

This will build image in the path where the compiling the JS and the image public path will automatically added.

If you're trying to add image from public path, you can initialise the origin path in the data section and call the image like follows

data:()=>{
  return {
    path: document.location.origin
  }
}

<img :src=`${path}/images/${user.photo}` alt="Profile Photo">

Note: you don't need to use this in the template section.

You should use require and point to the image.

Make sure that the path is relative to the module that uses it.

Write a function to return the image URL

var app = new Vue({
  el: '#app',
 methods: {
    getPicture() {
      return 'https://vuejs.org/images/logo.png'
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <img :src="getPicture()" alt="Profile Photo">
</div>

Related