1. 在应用界面中, 某个(些)元素的样式是变化的
class/style绑定就是专门用来实现动态样式效果的技术
2. 动态class绑定
:class=等号后的变量值 可以是字符串
:class=等号后 可以是对象
:class=等号后 可以是数组
3. 动态style绑定
:style="{ color: myPinkColor, fontSize: fontSize + 'px' }"
:style="{color: myPinkColor, fontSize: (fontSize > 8 ? fontSize : 10) + 'px'}
:style="{对象左边是css样式名: 右边是动态绑定的值 }
<template>
<div style="font-size: 14px;">
<h2>1. class绑定</h2>
<!-- 变量值可以写一个或多个class名 -->
<p class="text-center" :class="myClassAll">1个或多个class名</p>
<!-- class类名: 冒号右边的值如果为true则添加该类名,false则没有该类名 -->
<p :class="{'bg-pink': hasBgPink, 'color-fff': hasColorFff }"> :class=绑定方式是对象</p>
<p :class="['bg-pink', hasColorFff ? 'color-fff' : 'color-000' ]"> :class=绑定方式是数组</p>
<h2>2. style绑定</h2>
<p style="color:red; font-size: 30px">静态的style</p>
<p :style="{color: myPinkColor, fontSize: (fontSize > 8 ? fontSize : 10) + 'px'}">动态的style</p>
<!-- 点击更新动态绑定的class 和 style样式 -->
<button @click="updateClassStyle">更新</button>
</div>
</template>
<script lang="ts">
// vue3.0版本语法
import { defineComponent, ref, } from 'vue';
export default defineComponent({
name: "组件名",
setup() {
const myClassAll = ref('bg-pink color-fff')
const hasBgPink = ref(true)
const hasColorFff = ref(true)
const myPinkColor = ref('pink')
const fontSize = ref(10)
const updateClassStyle = () => {
// 动态更新class类名
hasBgPink.value =!hasBgPink.value
hasColorFff.value =!hasColorFff.value
// 动态更新style样式
myPinkColor.value = 'blue'
fontSize.value = 60
}
return {
myClassAll,hasBgPink,updateClassStyle,
hasColorFff,myPinkColor,fontSize
}
},
});
</script>
<style scoped>
.text-center {
text-align: center;
}
.bg-pink {
background-color: pink;
}
.color-fff {
color: #fff;
}
.color-000 {
color: #000;
}
</style>
页面显示效果:
点击更新按钮后的效果: