Search code examples
vue.jssvgbackground-colormask

Change dynamically background mask in vue js


in order to achieve "change svg icon color" easily, I choosed to used the mask method. Something like :

<template>
  <div class="side_bar_button">
    <div class="colored" :style="cssVars" />
  </div>
</template>

<script lang="ts">
import {  Vue } from 'vue-property-decorator';

export default Vue.extend({
    props: {
        bgColor: {
            type: String,
            default: "#0099CC"
        }
    },
    computed: {
        cssVars() {
            return {
                '--bg-color': this.bgColor
            }
        }
    }
})
</script>

<style scoped>
.colored {
  background-color: var(--bg-color); /* defines the background color of the image */
  mask: url('../assets/icon/icon_about.svg') no-repeat center / contain;
  height: 50px;
}

This is complicated but it works like a charm (except that I can't use @/assets/icon/icon_about.svg as path, but ../assets/etc...)

My goal now is to choose the mask through props:

<template>
  <div class="side_bar_button">
    <div class="colored" :style="cssVars" />
  </div>
</template>

<script lang="ts">
import {  Vue } from 'vue-property-decorator';

export default Vue.extend({
    props: {
        bgColor: {
            type: String,
            default: "#0099CC"
            },
        imgSrc: {
            type: String
        }
    },
    computed: {
        cssVars() {
            return {
                '--bg-color': this.bgColor,
                '--mask-src': require('../assets/' + this.imgSrc)
            }
        }
    }
})
</script>

<style scoped>
.colored {
  background-color: var(--bg-color); /* defines the background color of the image */
  mask: url(var(--mask-src)) no-repeat center / contain;
  height: 50px;
}

Unfortunaltely, I can't use url() with the var(--mask-src).

Have you a solution ?

Thank you


Solution

  • Ok got it...

    in JS simply type :

    '--mask-src': "url(" + require('@/assets/' + this.imgSrc) + ")" 
    

    and in CSS:

    mask: var(--mask-src) no-repeat center / contain;