Vue動態(tài)類的幾種使用方法總結
Vue動態(tài)類的幾種使用
動態(tài)類的操作比較簡單,但是很實用。
點擊顯示或隱藏樣式的做法
利用帶數據綁定
<button @click="isShow = !isShow">點擊</button>
<div :class="{ colorRed: isShow }">哈哈哈</div>data() {
? return {
? isShow: true
}.colorRed {
?? ?color:red;
}
.colorBlue{
?? ?color:blue;
}代碼含義:當isShow 為true時,添加類名colorRed ,div字體為紅色,渲染結果如下:
<div class="colorRed ">哈哈哈</div>
利用三元表達式切換樣式
控制isShow 切換樣式
<div :class="[isShow ?'colorRed':'colorBlue']">哈哈哈</div>
多個動態(tài)類的用法
案例 : 用帶有圖標的按鈕展開列表和收起列表

<i :class="{'el-icon-d-arrow-left':!menuIsShow,'el-icon-d-arrow-right': menuIsShow}"
class="el-icon-d-arrow-left openMenu"
@click="menuIsShow=!menuIsShow">
</i>
el-icon-d-arrow-left 是 element自帶的字體圖標
data() {
return {
menuIsShow: false
};
},
小結:利用動態(tài)類可以節(jié)省很多代碼,實現(xiàn)更復雜的功能。
Vue class動態(tài)類名
1. 三元表達式
//1. html
<view :class="`stage-${item.state == '通過' ? 'pass' : 'nopass'}`"></view>
?
//2.style
.stage-pass {
? ? background: green;
}
.stage-nopass {
? ? background: red;
}2. 對象的形式:可以寫多個,用逗號分開(常用)。
<div class="steps-list-cont" :class="{ stage: item.label == '繳納成功', 'stage-pass': true ?}"> </div>3.傳方法,在方法中返回類名,這個方法是可以觸發(fā)的哦~,或者通過計算屬性也是妥妥滴
// 使用方法?
<view :class="queryBoxClassNames()"></view>
?
methods: {
? ? // 動態(tài)獲取類名
? ? queryBoxClassNames() {
? ? ? ? const classNames = {
? ? ? ? ? ? JMJS: ['fixed-top', 'fixed-right']
? ? ? ? }
? ? ? ? return classNames[this.type] || ['fixed-bottom', 'fixed-left'];
? ? },
}
?
----------------------------------
?
// 使用計算屬性
<view :class="queryBoxClassNames"></view>
?
computed: {
? ? // 動態(tài)獲取類名
?? ?queryBoxClassNames() {
? ? ? ? const classNames = {
? ? ? ? ? ? JMJS: ['fixed-top', 'fixed-right']
? ? ? ? }
? ? ? ? return classNames[this.type] || ['fixed-bottom', 'fixed-left'];
? ? },相當于
<view v-if="fType !== 'JMJS'" class="fixed-bottom fixed-left"></view> <view v-if="fType == 'JMJS'" class="fixed-top fixed-right"></view>
4.根據計算屬性判斷添加類名,該寫法多用于被封裝的組件庫內
?<template>
? <transition name="mint-toast-pop">
? ? <div class="mint-toast" v-show="visible" :class="customClass" :style="{ 'padding': iconClass === '' ? '10px' : '20px' }"></div>
? </transition>
</template>
?
?
computed: {
? ? ? customClass() {
? ? ? ? var classes = [];
? ? ? ? switch (this.position) {
? ? ? ? ? case 'top':
? ? ? ? ? ? classes.push('is-placetop');
? ? ? ? ? ? break;
? ? ? ? ? case 'bottom':
? ? ? ? ? ? classes.push('is-placebottom');
? ? ? ? ? ? break;
? ? ? ? ? default:
? ? ? ? ? ? classes.push('is-placemiddle');
? ? ? ? }
? ? ? ? classes.push(this.className);
?
? ? ? ? return classes.join(' ');
? ? ? }
? ? }總結
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
vue 實現(xiàn)websocket發(fā)送消息并實時接收消息
這篇文章主要介紹了vue 實現(xiàn)websocket發(fā)送消息并實時接收消息,項目結合vue腳手架和websocket來搭建,本文給大家分享實例代碼,需要的朋友可以參考下2019-12-12
vue如何統(tǒng)一樣式(reset.css與border.css)
這篇文章主要介紹了vue如何統(tǒng)一樣式(reset.css與border.css),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-05-05

