我正在使用Vue.js,我想要更改CSS类属性。 使用该类的HTML代码如下:
<div class="fillTimerBar"></div>
CSS代码:
.fillTimerBar {
width: 100%;
height: 8px;
}
从那里我想使用Vue组件中的width
属性更改computed
类属性。
如果有的话,哪种方法会正确?
答案 0 :(得分:14)
您必须使用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';
}
}
})
&#13;
#myDiv{
background-color:red;
height:200px;
}
&#13;
<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>
&#13;
答案 1 :(得分:2)
要更改类中的属性,可以使用CSS自定义属性:
.fillTimerBar {
--width: 100%;
width: var(--width);
height: 8px;
}
在Vue中,您可以将CSS变量绑定到样式:
<div class="fillTimerBar" :style="`--width: ${computedWidth}`"></div>