Vue.js dynamic <style> with variables
The best way to include dynamic styles is to use CSS variables. To avoid inline styles while gaining the benefit (or necessity—e.g., user-defined colors within a data payload) of dynamic styling, use a <style>
tag inside of the <template>
(so that values can be inserted by Vue). Use a :root
pseudo-class to contain the variables so that they are accessible across the CSS scope of the application.
Note that some CSS values, like url()
cannot be interpolated, so they need to be complete variables.
Example (Nuxt .vue
with ES6/ES2015 syntax):
<template><div> <style> :root { --accent-color: {{ accentColor }}; --hero-image: url('{{ heroImage }}'); } </style> <div class="punchy"> <h1>Pow.</h1> </div></div></template><script>export default { data() { return { accentColor: '#f00', heroImage: 'https://vuejs.org/images/logo.png', }},}</script><style>.punchy { background-image: var(--hero-image); border: 4px solid var(--accent-color); display: inline-block; width: 250px; height: 250px;}h1 { color: var(--accent-color);}</style>
Also created an alternate more involved runnable example on Codepen.
As you are using vuejs, Use vuejs to change background instead css
var vm = new Vue({ el: '#vue-instance', data: { rows: [ {value: 'green'}, {value: 'red'}, {value: 'blue'}, ], item:"" }, methods:{ onTimeSlotClick: function(item){ console.log(item); document.querySelector(".dynamic").style.background = item; } }});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.16/vue.js"></script><div id="vue-instance"> <select class="form-control" v-model="item" v-on:change="onTimeSlotClick(item)"> <option value="">Select</option> <option v-for="row in rows"> {{row.value}} </option> </select> <div class='dynamic'>VALUE</div> <br/><br/> <div :style="{ background: item}">Another</div></div>