Javascript 使用 Vue.js 更改 CSS 类属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46195802/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:21:34  来源:igfitidea点击:

Change CSS class property with Vue.js

javascripthtmlcssvue.jsvuejs2

提问by Alex

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

我正在使用 Vue.js 并且我想更改 CSS 类属性。使用该类的 HTML 代码如下:

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

And the CSS code:

和 CSS 代码:

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

From there I want to change the widthclass property using a computedproperty from the Vue component.

从那里我想width使用computedVue 组件中的属性更改类属性。

Which would be correct way if any?

如果有的话,哪个是正确的方法?

回答by Mihai Alexandru-Ionut

You have to use v-bind:styledirective.

你必须使用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/[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>

回答by t k

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>