vue动态类的几种使用
动态类的操作比较简单,但是很实用。
点击显示或隐藏样式的做法
利用带数据绑定
<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>
多个动态类的用法
案例 : 用带有图标的按钮展开列表和收起列表

<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
};
},
小结:利用动态类可以节省很多代码,实现更复杂的功能。
vue class动态类名
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.传方法,在方法中返回类名,这个方法是可以触发的哦~,或者通过计算属性也是妥妥滴
// 使用方法
<view :class="queryboxclassnames()"></view>
methods: {
// 动态获取类名
queryboxclassnames() {
const classnames = {
jmjs: ['fixed-top', 'fixed-right']
}
return classnames[this.type] || ['fixed-bottom', 'fixed-left'];
},
}
----------------------------------
// 使用计算属性
<view :class="queryboxclassnames"></view>
computed: {
// 动态获取类名
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(' ');
}
}总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论