3👍
✅
Vue 3 with v-bind() in CSS
v-bind()
can be used to bind a reactive variable or computed property to a CSS property. Updating the CSS value is then as easy as updating the reactive variable.
<template>
<div>
<div class="box" />
<input v-model="lastPercent" type="range" min="1" max="100" />
</div>
</template>
<script>
export default {
data() {
return {
lastPercent: 60
}
},
computed: {
gradient() {
return `radial-gradient(circle, hsla(274, 75%, 37%, 1) 0%, hsla(280, 100%, 80%, 1) ${this.lastPercent}%`
}
}
}
</script>
<style>
.box {
width: 300px;
height: 300px;
background: v-bind(gradient);
}
</style>
Vue 2 with var()
Vue 2 is slightly more involved. You need to bind the computed variable to the element and also assign the variable in the styling with var()
. The syntax of var()
requires you precede the variable name with two hyphens, e.g. --variableName
<template>
<div>
<div class="box" :style="boxStyle" />
<input v-model="lastPercent" type="range" min="1" max="100" />
</div>
</template>
<script>
export default {
data() {
return {
lastPercent: 60
};
},
computed: {
boxStyle() {
return {
'--gradient': `radial-gradient(circle, hsla(274, 75%, 37%, 1) 0%, hsla(280, 100%, 80%, 1) ${this.lastPercent}%`
};
}
}
};
</script>
<style>
.box {
width: 300px;
height: 300px;
background: var(--gradient);
}
</style>
Source:stackexchange.com