Home > Back-end >  how to add Vue props value to background-image
how to add Vue props value to background-image

Time:01-31

I'm new in VueJS and I get confused to change background image from Vue props value.

I've created simple table from 'vue3-easy-data-table'.

BaseTable.vue:

<template>
  <EasyDataTable>
...
  </EasyDataTable>
</template>

<script setup lang="ts">
  changeImg: {
    type: String,
  }
})

</script>

<style>

.vue3-easy-data-table__message {
  
  background-image: url("`${v-bind("changeImg")}`");
  /*  background-image: var(--image-url); */
  /* background-image: url('@/assets/img/noDataMultiplierOnCity.svg'); */
 
}

</style>

View.vue:

<template>
<BaseTable
  :changeImg= "image"
  
/>     
</template>

<script lang="ts" setup>

const image : string = "'@/assets/img/noDataMultiplierOnCity.svg'" 

</script>

I've tried solution from this link enter image description here

code:

App.vue

<script setup>
import { ref } from 'vue'
import BaseTable from './BaseTable.vue'
import BaseTable2 from './BaseTable2.vue'

const msg = ref('Hello World!')
const imageUrl = ref("https://cdn.mos.cms.futurecdn.net/SWx64q2g3wax53Xz5H4QjS-970-80.jpg.webp");
</script>

<template>
  <h1>{{ msg }}</h1>
  <input v-model="msg">
  <BaseTable :image="imageUrl"/>
  <hr>
  <BaseTable2 :image="imageUrl"/>
</template>

BaseTable.vue

<template>
  <div  :style="backgroundStyles(image)">
    <h2>
      Base Table
    </h2>
    <ul v-for="index in 8" :key="index">
      <li>Index: {{ index }}</li>
    </ul>
  </div>
  
</template>

<script setup>
 const props = defineProps(['image'])
 
 const backgroundStyles = (img) => {
   return {
     'background-image': `url(${img})`,
     'background-size': 'cover'
   }
 }
</script>

<style scoped>
  .bkgrnd {
    color: white;
    font-style: bold;
  }
</style>

Solution using the prop in the CSS

Another way to do this can be to avoid inline styles and instead display the background image in the <style> CSS code. To do this, I would use a computed property to create a URL from the prop, something like:

const computedUrl = computed(() => {
  return `url(${props.image})`;
});

Code example,

BaseTable2.vue

<template>
  <div >
    <h2>
      Base Table 2
    </h2>
    <ul v-for="index in 8" :key="index">
      <li>Index: {{ index }}</li>
    </ul>
  </div>
  
</template>

<script setup>
import { computed } from 'vue';
const props = defineProps(['image'])

const computedUrl = computed(() => {
  return `url(${props.image})`;
});
</script>

<style scoped>
  .bkgrnd {
    color: white;
    font-style: bold;
    background-image: v-bind(computedUrl);
  }
</style>

Both examples can be found at the Vue SFC Playground

  • Related