1

I have a component that has a hover animation where 4 images are rotated in a loop:

animation: changeImg-1 2.5s linear infinite;

@keyframes changeImg-1 {
  0%, 100% { background-image: url('images/wel1.png'); }
  25% { background-image: url('images/wel2.png'); }
  50% { background-image: url('images/wel3.png'); }
  75% { background-image: url('images/wel4.png'); }
}

Now I want to make this component reusable by being able to pass image strings in as props, those get assigned as css variables which then get picked up by the animation.

I got as far as defining the css variable with a path in a computed property which is then used in the css:

computed: {
    userStyle () {
      return {
        '--myBackground': `url(${require('@/components/ImagesInText/images/wel1.png')})`,
      }
    }
  },

CSS:

.image {  
background:var(--myBackground); 
}

What I can't get to work is to pick up an image path from props and use it in the computed property...

   props: {
    image: { type: String, default: '@/components/ImagesInText/images/wel1.png' },
  },

If I do this below I get en error: Cannot find module '@/components/ImagesInText/images/wel1.png'"

computed: {
    userStyle () {
      return {

        '--myBackground': `url(${require( this.image )})`,
      }
    }
  },
martinval
  • 459
  • 4
  • 19

2 Answers2

0

When using a variable path/filename, require needs some assistance. You must hard code at least the first portion of the path as a string.

  • For example, this works:
const filename = 'wel1.png';
require('@/components/ImagesInText/images/' + filename); // <-- The string is needed
  • This works too:
const path = 'components/ImagesInText/images/wel1.png';
require('@/' + path); // <-- This is good enough too
  • But this would not work:
const fullpath = '@/components/ImagesInText/images/wel1.png';
require(fullpath); // <-- No. Can't infer the path from a variable only
Dan
  • 59,490
  • 13
  • 101
  • 110
0

As the way mentioned In this thread. it's working perfectly for me.

<div class="register-img" :style="{'background-image': 'url(' + require('@/assets/images/register-image.png') + ')'}"></div> 
M-Khawar
  • 855
  • 5
  • 17