首頁 > web前端 > js教程 > 主體

vue.js學習筆記之綁定style樣式和class列表

高洛峰
發布: 2017-01-12 13:14:46
原創
1248 人瀏覽過

資料綁定一個常見需求是操作元素的 class 清單和它的內聯樣式。因為它們都是 attribute,我們可以用 v-bind 處理它們:只需要計算表達式最終的字串。不過,字串拼接麻煩又易錯。因此,當 v-bind 用於 class 和 style 時,Vue.js 專門增強了它。表達式的結果類型除了字串之外,還可以是物件或陣列。

一.綁定Class屬性。

綁定資料用v-bind:指令,簡寫成:

語法:

。 class後面的雙引號裡接受一個物件字面量/物件參考/陣列作為參數,

這裡,{active: isActive}是物件參數,active是class名稱,isActive是一個布林值。以下是一個例子:

綁定物件字面量

html:

<div id="classBind">
<span :class="{warning:isWarning,safe:isSafe}" v-on:click="toggle">
状态:{{alert}}{{isSafe}}
</span>
</div>
//js
var app11=new Vue({
el:&#39;#classBind&#39;,
data:{
isWarning:true,
alertList:[&#39;红色警报&#39;,&#39;警报解除&#39;],
alert:&#39;&#39;
},
computed:{
isSafe:function(){
return !this.isWarning;
}
},
methods:{
toggle:function(){
this.isWarning=!this.isWarning;
this.alert= this.isWarning?this.alertList[0]:this.alertList[1];
}
}
});
登入後複製

css:

.warning{
color:#f24;
}
.safe{
color:#42b983;
}
登入後複製

當點擊狀態文字時,可以切換後面的文字和顏色

//狀態:警報解除警告/狀態:紅色警報false

綁定物件參考

這裡綁定的物件可以寫到Vue實例的data裡面,而在class="classObj ",雙引號中的class是Vue實例中classObj物件的引用。 classObj可以放在data中或computed中,如果在computed中,則classObj所對應的函數必須傳回一個物件如下:

js:

var app11=new Vue({
el:&#39;#classBind&#39;,
data:{
isWarning:true,
alertList:[&#39;红色警报&#39;,&#39;警报解除&#39;],
alert:&#39;&#39;
},
computed: {
isSafe: function () {
return !this.isWarning;
},
classObj:function(){
return {
warning: this.isWarning,
safe:this.isSafe
}
}
},
methods:{
toggle:function(){
this.isWarning=!this.isWarning;
this.alert= this.isWarning?this.alertList[0]:this.alertList[1];
}
}
});
登入後複製

綁定陣列

html:

rreee

css:

<div v-bind:class="classArray" @click="removeClass()">去掉class</div>
登入後複製

   

效果,點擊去掉class,會調用removeClass函數,去掉classArray數組的最後一項,第一次,去掉'red',字體顏色由紅變黑,再點,去掉'big ',字體變小。

二、綁定內聯style

此時此刻,我一邊看著本頁旁邊的那個Vue api文檔學,一邊到這裡賣,裝逼的感覺真爽o(^▽^)o

html

data: {
classArray:["big",&#39;red&#39;]
}
methods:{
removeClass:function(){
  this.classArray.pop();
}
}
登入後複製

css

這個不需要css。 。 。

js

.big{
font-size:2rem;
}
.red{
color:red;
}
登入後複製

除了傳入對象字面量以外,也可以傳入對象引用和數組給V-bind:style

以上所述是小編給大家介紹的vue.js學習筆記之綁定style和class,希望對大家有幫助,大家有任何疑問請給我留言,小編會及時回覆大家的。在此也非常感謝大家對PHP中文網的支持!

更多vue.js學習筆記之綁定style樣式和class列表相關文章請關注PHP中文網!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!