简体   繁体   English

用 Vue.js 更改 CSS class 属性

[英]Change CSS class property with Vue.js

I'm using Vue.js and I want to change a CSS class property.我正在使用 Vue.js 并且我想更改 CSS class 属性。 The HTML code which uses the class is the following:使用 class 的 HTML 代码如下:

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

And the CSS code: CSS 代码:

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

From there I want to change the width class property using a computed property from the Vue component.从那里我想使用 Vue 组件的computed属性更改width class 属性。

Which would be correct way if any?如果有的话,哪种方法是正确的?

You have to use v-bind:style directive.您必须使用v-bind:style指令。

 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/vue@2.4.3/dist/vue.js"></script> <div id="example"> <div id="myDiv" v-bind:style="{ width: computedWidth }"></div> <button v-on:click="changeWidth()">Change</button> </div>

To change a property inside a class, you can use CSS custom properties:要更改类中的属性,您可以使用 CSS 自定义属性:

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

In Vue, you can bind CSS variables to the style:在 Vue 中,您可以将 CSS 变量绑定到样式:

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

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. 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):如果您希望宽度为一半,则 CSS 代码(更具体的规则优先):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM