Frontend employee
Frontend employee

Reputation: 729

How can I apply variable to css in VueJS [no inline-styling]

I want to create a background color of body element that will dynamically change based on this.linearGradient. As you might see it should change a part of linear-gradient instead of replacing the entire linear-gradient. No inline-styling allows.

computed: {
  backgroundStyle () {
    return {
      '--linearGradient': this.linearGradient
    }
  }
},

<style>
background: linear-gradient(145.74deg, #9BDBFF -33.02%, #B4DEDA 52.01%, #FFD66B  var(--linearGradient)7.04%);
</style>
  <body :style="backgroundStyle">
    <div id="app"></div>
  </body>

Upvotes: 0

Views: 161

Answers (1)

Stark Buttowski
Stark Buttowski

Reputation: 1849

Please find the below snippet.

new Vue({
  el: "#app",
  template: '<div>bg-color<br/>Applied<input type="text" v-model="linearGradient" /></div>',
  data() {
    return {
      linearGradient: '#FFD66B'
    }
  },
  watch: {
    linearGradient: {
      immediate: true,
      handler(oldValue, newValue) {
        document.body.style.background = `linear-gradient(145.74deg, #9BDBFF -33.02%, #B4DEDA 52.01%,  ${oldValue} 7.04%)`
      }
    }
  },
  computed: {
    backgroundStyle: function() {
      return {
        background: `linear-gradient(145.74deg, #9BDBFF -33.02%, #B4DEDA 52.01%,  ${this.linearGradient} 7.04%)`
      }
    }
  }
})
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<div id="app"></div>

Upvotes: 1

Related Questions