26

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?

0

3 Answers 3

35

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>

Sign up to request clarification or add additional context in comments.

2 Comments

But in your case you changed direct style ,what about property inside class ?
what happened if there is something like text-decoration instead?
15

To change a property inside a class, you can use CSS custom properties:

.fillTimerBar {
    --width: 100%;
    width: var(--width);
    height: 8px;
}

In Vue, you can bind CSS variables to the style:

<div class="fillTimerBar" :style="`--width: ${computedWidth}`"></div>

1 Comment

And for multiple variables in css you can use following: :style="`--var-1: ${computed1}; --var-2: ${computed3}; --var-3: ${computed3};"`
0

You can use plain old javascript to add a new class to your div, then add css properties to elements that have the new class and your existing class. The CSS code if you wanted the width to be half (the more specific rule takes precedence):

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.