【问题标题】:Change CSS class property with Vue.js使用 Vue.js 更改 CSS 类属性
【发布时间】:2018-02-22 01:29:58
【问题描述】:

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

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

还有 CSS 代码:

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

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

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

【问题讨论】:

    标签: javascript html css vue.js vuejs2


    【解决方案1】:

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

    【讨论】:

    • 但是在您的情况下,您更改了直接样式,那么类内的属性呢?
    • 如果改用 text-decoration 会发生什么?
    【解决方案2】:

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

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

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

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

    【讨论】:

    • 对于 css 中的多个变量,您可以使用以下内容::style="`--var-1: ${computed1}; --var-2: ${computed3}; --var-3: ${computed3};"`
    猜你喜欢
    • 2012-07-13
    • 1970-01-01
    • 2020-10-27
    • 1970-01-01
    • 2018-03-15
    • 2011-08-18
    • 2016-01-09
    • 2013-09-25
    • 2013-05-08
    相关资源
    最近更新 更多