1

I want to display a picture from assets folder based on some property value. I have created a method with a switch. The picture was not found. After some googling I realized that this is caused by webpack and I shall use require. But I still encounter strange errors.

This works:

<img src="@/assets/happy.png" class="pr-2" align="middle">

Dynamic:

<img :src="this.votedPicture" class="pr-2" align="middle">

votedPicture() {
  switch (this.$store.getters.POLL.my_vote) {
    case 'neutral':
      return require('@/assets/happy.png');
    default:
      return require('@/assets/angry.png');
  }
},

},

This fails with Unexpected require().

When I move the require to img:

<img :src="require(this.votedPicture)" class="pr-2" align="middle">

there is an error in console:

vue.runtime.esm.js:1888 Error: Cannot find module '@/assets/happy.png'
at webpackEmptyContext (organisms sync:2)
at Proxy.render (CompletePoll.vue?4b27:31)
at VueComponent.Vue._render (vue.runtime.esm.js:3548)

So what is the proper way?

7
  • Have you tried referencing the image from your public folder? Commented May 17, 2020 at 17:56
  • According to documentation this is not recommended Commented May 17, 2020 at 17:56
  • Your images wont be processed by webpack.. You will store the images in the public folder right? So when you build your project, the files will be moved over to your dist folder Commented May 17, 2020 at 18:04
  • It should be :src="votedPicture", no this prefix required Commented May 17, 2020 at 23:55
  • "This fails with Unexpected require()" 👈 What exactly is the error message here and where do you see it? Commented May 18, 2020 at 0:07

1 Answer 1

1

It's just an Eslint rule. It fails because of eslint-plugin from vue-cli I guess. Try creating an .eslintrc file containing

{
  rules: {
    "global-require": 0  
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

I turned it off for the current line and it works now: // eslint-disable-next-line global-require

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.