Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change CSS class property with Vue.js

Tags:

I'm using Vue.js and I want to change a CSS class property. The HTML code which uses the class is the following:

<div class="fillTimerBar"></div> 

And the CSS code:

.fillTimerBar {         width: 100%;         height: 8px;  } 

From there I want to change the width class property using a computed property from the Vue component.

Which would be correct way if any?

like image 659
Alex Avatar asked Sep 13 '17 11:09

Alex


People also ask

How do I change CSS properties of a class?

Set Style Using element. One can use element. className to change various style parameters of an HTML element by clubbing those as a class and assigning the class name to the selected element with element. className . This method is helpful, especially in scenarios where we need to display an error in an input field.

How do I change my Vue style?

Vue. js provides style binding that you can use to change the style dynamically. You can bind a variable to the style attribute in any HTML tag and change the style when the bound variable is changed.

Can you change a CSS class with JavaScript?

With JavaScript, we are able to set CSS styles for one or multiple elements in the DOM, modify them, remove them or even change the whole stylesheet for all your page.

How do I override Vue CSS?

The only way to override the css is to get higher points of specificity. For example, adding the class . btn to the selector gets the same two points but it still looses because of the order of precedence. So, if we add another selector like .


1 Answers

You have to use v-bind:style directive.

var vm = new Vue({    el: '#example',    data: {       width:'200px'    },    computed: {      computedWidth: function () {        return this.width;      }    },    methods: {      changeWidth: function (event) {        this.width='100px';      }    }  })
#myDiv{    background-color:red;    height:200px;  }
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>    <div id="example">    <div id="myDiv" v-bind:style="{ width: computedWidth }"></div>    <button v-on:click="changeWidth()">Change</button>  </div>
like image 189
Mihai Alexandru-Ionut Avatar answered Oct 18 '22 05:10

Mihai Alexandru-Ionut