为了方便开发者进行样式控制, Vue 扩展了 v-bind 的语法,可以针对 class 类名 和 style 行内样式进行控制 。
语法:<div :class = "对象/数组">这是一个div</div>
当class动态绑定的是对象时,键就是类名,值就是布尔值,如果值是true,就有这个类,否则没有这个类
适用场景:一个类名,来回切换
<div class="box" :class="{ 类名1: 布尔值, 类名2: 布尔值 }"></div>
当class动态绑定的是数组时 → 数组中所有的类,都会添加到盒子上,本质就是一个 class 列表
使用场景:批量添加或删除类
<div class="box" :class="[ 类名1, 类名2, 类名3 ]"></div>
以下为两种方式的演示代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
.box{height: 60px;width: 100px;color: blue;border: 5px solid black;}
.box2{width: 30px;}
.red{background: red;}
</style>
<body>
<div id="app">
<div class="box" :class="{ red: true }">盒子1</div>
<div class="box" :class="[red]">盒子2</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2.7.16/dist/vue.js"></script>
<script>
const app=new Vue({
el:'#app',
data:{
}
})
</script>
</body>
</html>
演示过后如上图所示,现在我们再添加box2属性,后面的属性会把前面的属性重复的覆盖掉,比如:
<div class="box" :class="{ 'red': true ,'box2':true}">盒子1</div>
<div class="box" :class="['red','box2']">盒子2</div>
接下来是tab栏切换导航高亮的案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
* {
margin: 0;
padding: 0;
}
ul {
display: flex;
border-bottom: 2px solid #e01222;
padding: 0 10px;
}
li {
width: 100px;
height: 50px;
line-height: 50px;
list-style: none;
text-align: center;
}
li a {
display: block;
text-decoration: none;
font-weight: bold;
color: #333333;
}
li a.active {
background-color: #e01222;
color: #fff;
}
</style>
<body>
<div id="app">
<ul>
<li v-for=" (item,index) in list" :key="item.id" @click=" activeindex=index ">
<a :class="{active:index===activeindex}" href='#'>{{ item.name }}</a>
</li>
</ul>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2.7.16/dist/vue.js"></script>
<script>
const app=new Vue({
el:'#app',
data:{
activeindex:0,//记录高亮
list:[
{id:1,name:'京东秒杀'},
{id:2,name:'每日特价'},
{id:3,name:'品类秒杀'}
]
}
})
</script>
</body>
</html>
运行结果如下图所示
-
v-for="(item, index) in list"
:这是Vue.js中的一个指令,用于循环遍历list
数组,并为每个项目创建一个<li>
元素。它遍历数组list
,将每个项目分配给item
,将其相应的索引分配给index
。href='#'
:这将<a>
元素的href
属性设置为#
,使其成为一个伪链接。 :key="item.id"
:为每个渲染的元素提供唯一标识符。它使用列表中每个项目的id
属性作为唯一键。@click="activeindex=index"
:事件监听器,监听每个<li>
元素的点击事件。当点击时,它将activeindex
数据属性设置为循环的当前索引,有效跟踪了点击项目的索引。:class="{ active: index===activeindex }"
:这是Vue.js中用于动态绑定类到元素的语法。如果条件index===activeindex
评估为true,则将类active
应用于<a>
元素。因此,当当前项目的索引与activeindex
匹配时,它会将active
类添加到<a>
元素。