[英]Change CSS class property with Vue.js
我正在使用 Vue.js 並且我想更改 CSS class 屬性。 使用 class 的 HTML 代碼如下:
<div class="fillTimerBar"></div>
CSS 代碼:
.fillTimerBar {
width: 100%;
height: 8px;
}
從那里我想使用 Vue 組件的computed
屬性更改width
class 屬性。
如果有的話,哪種方法是正確的?
您必須使用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>
要更改類中的屬性,您可以使用 CSS 自定義屬性:
.fillTimerBar {
--width: 100%;
width: var(--width);
height: 8px;
}
在 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. 如果您希望寬度為一半,則 CSS 代碼(更具體的規則優先):
.fillTimerBar {
width: 100%;
height: 8px;
}
.fillTimerBar .HalfWidth {
width: 50%;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.