vue.js之綁定class和style

來源:互聯網
上載者:User

標籤:remove   code   att   name   而在   雙引號   iss   color   對象引用   

一.綁定Class屬性。

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

文法:<div v-bind:class="{ active: isActive }"></div>。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:‘#classBind‘, data:{ isWarning:true, alertList:[‘紅色警報‘,‘警報解除‘], alert:‘‘ }, 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;}

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

//狀態:警報解除true

//狀態:紅色警報false

綁定對象引用

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

js:

var app11=new Vue({    el:‘#classBind‘,    data:{        isWarning:true,        alertList:[‘紅色警報‘,‘警報解除‘],        alert:‘‘    },    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:

<div v-bind:class="classArray" @click="removeClass()">去掉class</div>

 

js

data: {classArray:["big",‘red‘]}
methods:{
removeClass:function(){
  this.classArray.pop();
}
}

css:

.big{    font-size:2rem;}.red{     color:red;    }

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

vue.js之綁定class和style

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.