我为什么要将v-bind用于样式

时间:2018-05-24 07:31:35

标签: vue.js vuejs2

我刚刚开始学习Vue,我很想知道,为什么我应该使用v-bind作为样式而不是在html / css文件中定期编写

1 个答案:

答案 0 :(得分:0)

假设您需要创建一个非静态的进度条。然后,您需要为示例更新样式属性width

为此,我们需要以编程方式编辑元素的width。我们'不能'在普通的CSS中,因此:style属性派上用场。

让我们创建一个例子: Codepen

HTML

<div id="vue">
  <div class="progress-bar">
    <div :style="{'width':progress + '%'}" class="progress" />
  </div>
  <button @click="fakeProgress">Init fake progress</button>
</div>

的CSS;

.progress-bar, .progress {
  border-radius: 20px;
  height: 20px;
} 
.progress-bar {
  width: 250px;
  background-color: gray;
}

.progress {
  background-color: blue;
  width: 0;
  transition: all 1s ease;
}

的Javascript

new Vue({
  el: '#vue',
  data: {
    progress: 0
  },
  methods: {
    fakeProgress() {
      let progress = setInterval(() => {
        if(this.progress == 100) {
         clearInterval(progress) 
        } else {
         this.progress += 1;
        }
      }, 50)
    }
  }
})

如您所见,我们将进度数据属性绑定到伪进度条上的宽度值。这只是一个简单的例子,但我希望这能让你看到它的潜力。 (您可以使用<progress>标记实现同样的效果,但这会破坏解释。

EDIT;还要指出你应该像你在问题中指出的那样正常地编写所有css。但是,:style用于通常无法使用css的情况。就像上面的例子一样,我们需要从变量中改变css。