3

The issue I'm having is using vue.js with webpack.

I have a list that I want to dynamically populate in vue.js.

I am using v-for to iterate over each object and create the list items.

To bind a img src tag to data point {{resource.img}} it looks like this: <img v-bind:src="resource.img"> to dynamically load an image.

However, when the client renders the page, the src path is correct, however it is the actual relative path (e.g. "../assets/example.png" etc, instead of the path webpack outputs. Thus, the image creates a 404 because there is no image at "../assets/example.png".

Alternatively, if I hardcode the src the image loads, and the the src is some path that webpack created, finding the correct image.

How can I dynamically set the src with webpack and vue.js?

1 Answer 1

10

You need require.context.

For example:

<img width="30" height="30" :src="imgUrl(resource.img)">

var images = require.context('../../assets/img/', false, /\.jpg$/)

export default {
  methods: {
    imgUrl: function (path) {
      return images('./' + path)
    }
  }
}

The require.context will essentially map the source path to the final path in the build directory for any image that it found in the source folder. This is how the imgUrl() method will return the right path at runtime.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.