动态类名
对象语法
使用对象语法绑定动态类名:
<template>
<div>
<button @click="toggleClass">Toggle Class</button>
<div :class="{'active': isActive, 'inactive': !isActive}">
This div's class changes dynamically.
</div>
</div>
</template>
<script>
export default {
data() {
return {
isActive: false
};
},
methods: {
toggleClass() {
this.isActive = !this.isActive;
}
}
}
</script>
<style>
.active {
background-color: green;
color: white;
}
.inactive {
background-color: red;
color: white;
}
</style>
数组语法
使用数组语法绑定动态类名:
<template>
<div>
<button @click="toggleClass">Toggle Class</button>
<div :class="[isActive ? 'active' : 'inactive', 'common-class']">
This div's class changes dynamically.
</div>
</div>
</template>
<script>
export default {
data() {
return {
isActive: false
};
},
methods: {
toggleClass() {
this.isActive = !this.isActive;
}
}
}
</script>
<style>
.active {
background-color: green;
color: white;
}
.inactive {
background-color: red;
color: white;
}
.common-class {
padding: 10px;
border: 1px solid #ccc;
}
</style>
动态样式
对象语法
使用对象语法绑定动态样式:
<template>
<div>
<button @click="toggleStyle">Toggle Style</button>
<div :style="divStyle">
This div's style changes dynamically.
</div>
</div>
</template>
<script>
export default {
data() {
return {
isStyled: false
};
},
computed: {
divStyle() {
return {
backgroundColor: this.isStyled ? 'blue' : 'yellow',
color: this.isStyled ? 'white' : 'black',
padding: this.isStyled ? '20px' : '10px'
};
}
},
methods: {
toggleStyle() {
this.isStyled = !this.isStyled;
}
}
}
</script>
<style>
/* Optional: base styles for the div */
</style>
数组语法
使用数组语法绑定动态样式(不太常见,因为样式一般是以对象形式存在,但可以通过计算属性返回一个数组来实现):
<template>
<div>
<button @click="toggleStyle">Toggle Style</button>
<div :style="styleArray">
This div's style changes dynamically.
</div>
</div>
</template>
<script>
export default {
data() {
return {
isStyled: false
};
},
computed: {
styleArray() {
return [
{ backgroundColor: this.isStyled ? 'blue' : 'yellow' },
{ color: this.isStyled ? 'white' : 'black' },
{ padding: this.isStyled ? '20px' : '10px' }
];
}
},
methods: {
toggleStyle() {
this.isStyled = !this.isStyled;
}
}
}
</script>
<style>
/* Optional: base styles for the div */
</style>
使用场景
-
对象语法:
- 当你需要根据多个布尔条件动态地添加或移除类时,使用对象语法非常方便。
- 例如,当你需要根据某个状态设置多个不同的类时。
-
数组语法:
- 当你需要在动态类名或样式中包含固定类或样式时,数组语法非常有用。
- 例如,当你需要始终应用某些类,同时根据条件添加或移除其他类时。
通过这两种语法,你可以灵活地在Vue 2中动态设置类名和样式,以适应不同的需求。