VUE JS Dynamic background image after axios request

Viewed 704

I'm trying to display a background image that it's path needs to be loaded through an API. The plan is: From a main grid of links, click one and display a background image according to the one clicked.

As of now I am using axios to query my API which sends the data I need. I have the following script part on my component.

<script>
import axios from 'axios'
const lhost = require("@/config/global").host;

let championData;

export default {
  name: 'IndividualChampion',
  props: {
    
  },
  data: () => ({
    champions: [],
    verPersonagem: mdiMovieOpen,
    
  }),
  computed: {
       
  },
  created: async function() {
      try {
        let champion = this.$route.fullPath.split('/')[2];
        let response = await axios.get(lhost + "/champion/" + champion + '/full');
        championData = response.data
        console.log(championData)
        let background = '@/assets' + championData['skins']['0']['splash'].replace('.png','.jpg')

    } 
    catch (e) {
      return e; 
    }
  },
  methods: { 

  }
  
}
</script>

And this is my HTML

<template>
    <div :style="{ backgroundImage: `url(${require(background)})` }">

    </div>
</template>

I have searched but can't seem to find a solution in which the background image is loaded and, when loaded, is presented. Can someone help?

1 Answers

Judging from your use of '@/assets', you seem to be using webpack with a resolve alias. The expression require(background) is not enough for webpack to determine what files it needs to add to your bundle.

You can help Webpack by specifying the directory that you want to load your file from. All you have to do is take out '@/assets/' from the background variable and use it directly in the require call so that Webpack can see it.

<template>
    <div v-if="background" :style="{ backgroundImage: `url(${require('@/assets/' + background)})` }">

    </div>
</template>
<script>
import axios from 'axios'
const lhost = require("@/config/global").host;

let championData;

export default {
  name: 'IndividualChampion',
  props: {
    
  },
  data: () => ({
    champions: [],
    verPersonagem: mdiMovieOpen,
    background: ''
  }),
  computed: {
       
  },
  created: async function() {
      try {
        let champion = this.$route.fullPath.split('/')[2];
        let response = await axios.get(lhost + "/champion/" + champion + '/full');
        championData = response.data
        console.log(championData)
        this.background = championData['skins']['0']['loading'].replace('.png','.jpg')

    } 
    catch (e) {
      return e; 
    }
  },
  methods: { 

  }
  
}
</script>

It will bundle every possible file inside the directory, though.

You can read more about it here: https://webpack.js.org/api/module-methods/#dynamic-expressions-in-import

Related