样式绑定
class样式和style样式的绑定
1.class样式
写法:class="xxx" xxx可以是字符串、对象、数组
- 字符串写法适用于:类名不确定,要动态获取
- 对象写法适用于:要绑定多个样式,个数不确定、名字也不确定
- 数组写法适用于:要绑定多个样式,个数确定,名字也确定,但不确定用不用
2.style样式
- :style="{fontSize:xxx}" 其中xxx是动态值
- :style="[a,b]" 其中a,b是样式对象
<template>
<!-- 绑定class样式--字符串写法,适用于:样式的类名不确定,需要动态指定 -->
<div
class="basic"
:class="mood"
@click="changeClass"
>
test
</div>
<!-- 绑定class样式--数组写法,适用于:要绑定的样式个数不确定、名字也不确定 -->
<div
class="basic"
:class="classArr"
@click="changeClass"
>
test
</div>
<!-- 绑定class样式--对象写法,适用于:要绑定的样式个数和名字确定 -->
<div
class="basic"
:class="classObj"
@click="changeClass"
>
test
</div>
<!-- 绑定style样式--对象写法 -->
<div
class="basic"
:style="styleObj"
@click="changeClass"
>
test
</div>
<!-- 绑定样式--数组写法 -->
<div
class="basic"
:style="styleArr"
@click="changeClass"
>
test
</div>
</template>
<script setup>
import { watch,ref,reactive} from 'vue'
let mood=ref('happy')
let classArr=reactive(['big','toobig'])
let classObj=reactive({
big:true,
toobig:false,
radius:true
})
let styleObj=reactive({
width:100,
height:100,
backgroundColor:'red'
})
const changeClass=()=>{
const arr=['normal','sad','happy']
const index=Math.floor(Math.random()*3)
mood.value=arr[index]
classArr.push('radius')
}
</script>
<style>
.basic{
width: 100%;
height: 50px;
border: 1px solid black;
}
.normal{
background-color: aqua;
}
.sad{
background-color: brown;
}
.happy{
background-color: cadetblue;
}
.big{
font-size: 20px;
}
.toobig{
font-size: 100px;
}
.radius{
border-radius: 10px;
}
</style>

浙公网安备 33010602011771号