2017-09-13 151 views
3

我正在使用Vue.js,我想更改CSS類屬性。 它使用類的HTML代碼如下:用Vue.js更改CSS類屬性

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

而且CSS代碼:

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

從那裏,我想用從computed屬性來更改width類屬性Vue組件。

如果有的話,這將是正確的方式?

回答

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/[email protected]/dist/vue.js"></script> 
 

 
<div id="example"> 
 
    <div id="myDiv" v-bind:style="{ width: computedWidth }"></div> 
 
    <button v-on:click="changeWidth()">Change</button> 
 
</div>

+1

就像一個魅力!謝謝 – Alex

0

new Vue({ 
 
\t el: '#app', 
 
    data: { 
 
    \t shapes: [ 
 
    \t { shape: 'circle' }, 
 
    
 
    ] 
 
    } 
 
});
.shape { 
 
    width: 150px; 
 
    height: 150px; 
 
    float: left; 
 
    margin: 10px; 
 
} 
 

 
.circle { 
 
    background-color: red; 
 
    border-radius: 50%; 
 
} 
 

 
.square { 
 
    background-color: blue; 
 
} 
 

 
.triangle { 
 
    width: 0; 
 
    height: 0; 
 
} 
 

 
.triangle.up { 
 
    border-left: 100px solid transparent; 
 
    border-right: 100px solid transparent; 
 
    border-bottom: 150px solid orange; 
 
} 
 

 
.triangle.right { 
 
    border-top: 100px solid transparent; 
 
    border-bottom: 100px solid transparent; 
 
    border-left: 150px solid green; 
 
} 
 

 
.triangle.down { 
 
    border-left: 100px solid transparent; 
 
    border-right: 100px solid transparent; 
 
    border-top: 150px solid #49A5C4; 
 
} 
 

 
.triangle.left { 
 
    border-top: 100px solid transparent; 
 
    border-bottom: 100px solid transparent; 
 
    border-right: 150px solid #A549C4; 
 
} 
 

 
/* Animations */ 
 
.fillTimerBar.animate { 
 
    animation-name: stretch; 
 
    animation-duration: 1.0s; 
 
    animation-timing-function: ease-out; 
 
} 
 

 
@keyframes stretch { 
 
    0% { 
 
    transform: scale(.3); 
 
    } 
 
    100% { 
 
    transform: scale(1.0); 
 
    } 
 
}
<script src="https://unpkg.com/vue/dist/vue.js"></script> 
 

 

 
<div id="app"> 
 
    <div class="shape" 
 
     v-for="shape in shapes" 
 
     v-bind:class="[ shape.shape, shape.direction ? shape.direction : '', { animate: shape.animate } ]"> 
 
      
 
     </div> 
 
</div>