使用 Vue.js 更改 CSS 类属性

新手上路,请多包涵

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

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

和CSS代码:

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

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

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

原文由 Alex 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 592
2 个回答

您必须使用 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>

原文由 Mihai Alexandru-Ionut 发布,翻译遵循 CC BY-SA 3.0 许可协议

要更改类中的属性,可以使用 CSS 自定义属性:

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

在 Vue 中,您可以将 CSS 变量绑定到样式:

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

原文由 t k 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题