VUE動態(tài)綁定class類的三種常用方式及適用場景詳解
更新時間:2025年01月16日 10:53:04 作者:zhangXiaoWei001
文章介紹了在實際開發(fā)中動態(tài)綁定class的三種常見情況及其解決方案,包括根據不同的返回值渲染不同的class樣式、給模塊添加基礎樣式以及根據設計確定是否使用多個樣式
前言
在實際開發(fā)中,我們會經常遇到動態(tài)綁定class的情況,常見的情況可能有:
- 根據不同的返回值渲染不同的class樣式(也就是兩個及兩個以上的動態(tài)class選擇使用);
- UI在設計時對于某個模塊的樣式沒有確定下來的時候我們去寫這個模塊(給了基礎樣式);
- UI在設計對于某個模塊的樣式有很多樣子,但不確定用是否全部使用時(給了基礎樣式)。
針對這三種常見的情況我們在寫頁面樣式時可已選擇這三種常見的動態(tài)加載calss的方法。
1.動態(tài)選擇class樣式(對象添加:情景一)
<template>
<div>
<div class="basic" :class="classObj">選擇添加樣式</div>
<div style="display: flex; flex-direction: column;">
<button style="width: 200px;" @click="chooseClass">選擇添加cs_class1類</button>
<button class="btn" @click="chooseClass3">選擇添加cs_class3類</button>
</div>
</div>
</template>
<script>
export default{
data() {
return {
classObj:{
cs_class1:false,
cs_class3:false,
},
}
},
methods:{
chooseClass(){
this.classObj.cs_class1=true
this.classObj.cs_class3=false
},
chooseClass3(){
this.classObj.cs_class1=false
this.classObj.cs_class3=true
}
}
}
</script>
<style>
.basic{
display: flex;
align-items: center;
justify-content: center;
background: pink;
width: 200px;
height: 100px;
}
.btn{
width: 200px;
margin-bottom: 20px;
}
.box_rudis{
border-radius: 30px;
}
.cs_class1{
color: red;
}
.cs_class2{
border:2px solid #0000FF
}
.cs_class3{
background: yellow;
}
</style>2.動態(tài)添加一個class樣式(字符串添加:情景二)
<template>
<div>
<div class="basic" :class="boxrudius">添加一個動態(tài)樣式</div>
</div>
</template>
<script>
export default{
data() {
return {
boxrudius:'box_rudis',
}
},
}
</script>
<style>
.basic{
display: flex;
align-items: center;
justify-content: center;
background: pink;
width: 200px;
height: 100px;
}
.box_rudis{
border-radius: 30px;
}
</style>3.動態(tài)添加多個class樣式(數組添加:情景三)
<template>
<div>
<div class="basic" :class="classArr">添加多個動態(tài)樣式</div>
<button class="btn" @click="addClassArr">動態(tài)添加多個class類</button>
</div>
</template>
<script>
export default{
data() {
return {
classArr:[],
}
},
methods:{
addClassArr(){
this.classArr=['cs_class1','cs_class2','cs_class3']
},
}
}
</script>
<style>
.basic{
display: flex;
align-items: center;
justify-content: center;
background: pink;
width: 200px;
height: 100px;
}
.btn{
width: 200px;
margin-bottom: 20px;
}
.box_rudis{
border-radius: 30px;
}
.cs_class1{
color: red;
}
.cs_class2{
border:2px solid #0000FF
}
.cs_class3{
background: yellow;
}
</style>總結
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

