Home > Blockchain >  I can't make a dynamic background image in vuejs, the url doesn't work
I can't make a dynamic background image in vuejs, the url doesn't work

Time:02-22

Im trying to make 6 blocks with different background images, i tried different options but none of them works,

This works:

<div :style="{ backgroundImage: `url(${require('../assets/images/img/img-1.jpg')})` }"></div>

These two doesnt work even if 'test' is literally the right path for the img:

<div :style="{ backgroundImage: `url(${require(test)})` }"></div>
<div  :style="{ backgroundImage: 'url('   require(test)   ')' }"></div>
<script>
export default {
   name: "Component",
   data() {
      return {
         test: "../assets/images/img/img-1.jpg",
         cardImgPath: "../assets/images/img/",
         images: [
            { img: "img-1.jpg" },
            { img: "img-2.jpg" },
            { img: "img-3.jpg" },
            { img: "img-4.jpg" },
            { img: "img-5.jpg" },
            { img: "img-6.jpg" },
         ],
      };
   },
};
</script>

CodePudding user response:

Given the usage of require(), I'm assuming your project is a Webpack-based project (scaffolded from Vue CLI).

The require() argument cannot be a fully dynamic expression for the same reason that import() calls cannot:

Dynamic expressions in import()

It is not possible to use a fully dynamic import statement, such as import(foo). Because foo could potentially be any path to any file in your system or project.

The import() must contain at least some information about where the module is located. Bundling can be limited to a specific directory or set of files so that when you are using a dynamic expression - every module that could potentially be requested on an import() call is included. For example, import(`./locale/${language}.json`) will cause every .json file in the ./locale directory to be bundled into the new chunk. At run time, when the variable language has been computed, any file like english.json or german.json will be available for consumption.

// imagine we had a method to get language from cookies or other storage
const language = detectVisitorLanguage();
import(`./locale/${language}.json`).then((module) => {
  // do something with the translations
});

In your case, you could change your require() argument to include the image's path directory:

<div v-for="image in images"
    :style="{ backgroundImage: `url(${require('../assets/images/img/'   image.img)})` }" ></div>
<script>
export default {
   data() {
      return {
         images: [
            { img: "img-1.jpg" },
            { img: "img-2.jpg" },
            { img: "img-3.jpg" },
            { img: "img-4.jpg" },
            { img: "img-5.jpg" },
            { img: "img-6.jpg" },
         ],
      };
   },
};
</script>
  • Related