一、开篇:为什么你的CSS类名写得像老太太的裹脚布?
记得我刚学前端那会儿,写个动态类名简直要命。一大堆if-else判断,字符串拼接得眼花缭乱,最后代码长得像老太太的裹脚布——又臭又长。
直到我遇见了Vue的class绑定,好家伙,原来写样式可以这么优雅!
想象一下这个场景:你要给按钮添加不同状态的颜色。普通写法可能是这样的:
// 传统写法 - 简直是在写JavaScript版的心情日记
let className = 'btn';
if (isActive) className += ' active';
if (hasError) className += ' text-danger';
if (isDisabled) className += ' disabled';
而Vue的class绑定写法:
<!-- Vue写法 - 简洁得像在写诗 -->
<button :class="{
'btn': true,
'active': isActive,
'text-danger': hasError,
'disabled': isDisabled
}">点击我</button>
是不是感觉从原始社会一下子穿越到了未来世界?别急,接下来我就带你深入探索Vue class绑定的三大法宝!
二、对象语法:给元素穿上“智能衣服”
对象语法是Vue class绑定中最常用、最直观的方式。它的核心理念很简单:类名作为键,条件作为值。值为真时类名生效,为假时自动消失。
基础用法:让按钮根据状态“变脸”
咱们来看个实际案例——一个会根据状态改变样式的按钮:
<template>
<div id="app">
<!-- 动态按钮组件 -->
<button
:class="{
'base-btn': true,
'btn-primary': type === 'primary',
'btn-danger': type === 'danger',
'btn-disabled': disabled,
'loading': isLoading
}"
@click="handleClick"
:disabled="disabled"
>
{
{ buttonText }}
</button>
<!-- 控制面板 -->
<div class="control-panel">
<button @click="changeType('primary')">主要按钮</button>
<button @click="changeType('danger')">危险按钮</button>
<button @click="toggleDisabled">切换禁用状态</button>
<button @click="toggleLoading">切换加载中</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
type: 'primary', // primary | danger
disabled: false,
isLoading: false
}
},
computed: {
buttonText() {
if (this.isLoading) return '加载中...';
if (this.disabled) return '已禁用';
return this.type === 'primary' ? '主要按钮' : '危险按钮';
}
},
methods: {
changeType(newType) {
this.type = newType;
},
toggleDisabled() {
this.disabled = !this.disabled;
},
toggleLoading() {
this.isLoading = !this.isLoading;
},
handleClick() {
if (!this.disabled && !this.isLoading) {
alert('按钮被点击了!');
}
}
}
}
</script>
<style scoped>
.base-btn {
padding: 12px 24px;
border: none;
border-radius: 6px;
font-size: 16px;
cursor: pointer;
transition: all 0.3s ease;
margin: 10px;
}
.btn-primary {
background-color: #1890ff;
color: white;
}
.btn-primary:hover {
background-color: #40a9ff;
}
.btn-danger {
background-color: #ff4d4f;
color: white;
}
.btn-danger:hover {
background-color: #ff7875;
}
.btn-disabled {
opacity: 0.6;
cursor: not-allowed !important;
}
.loading {
position: relative;
color: transparent;
}
.loading::after {
content: '';
position: absolute;
width: 16px;
height: 16px;
border: 2px solid transparent;
border-top: 2px solid currentColor;
border-radius: 50%;
animation: spin 1s linear infinite;
top: 50%;
left: 50%;
margin-top: -8px;
margin-left: -8px;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.control-panel {
margin-top: 20px;
}
.control-panel button {
margin: 0 5px;
padding: 8px 16px;
background: #f0f0f0;
border: 1px solid #d9d9d9;
border-radius: 4px;
cursor: pointer;
}
</style>
代码解读:
base-btn是始终存在的基础样式btn-primary和btn-dange

最低0.47元/天 解锁文章

被折叠的 条评论
为什么被折叠?



