vue实现tab栏功能描述
选项卡切换选中状态
实现效果
vue实现tab栏实现步骤
1. 概念理解
了解vue的基础指令
代码 | 含义 |
---|---|
v-on | 绑定事件,可以简写为:事件名=“执行体”。当触发事件时,执行执行体内的代码 |
v-for | 映射数据,v-for((item,index) in 数组)。将数组内数据映射到页面上 |
:属性名=属性值:判断条件 | 当条件为true时,让赋予属性名属性值 |
Html框架
<div id="app">
<ul>
<li>
<a href="#"></a>
</li>
</ul>
</div>
2. Tab栏切换
定义一个arrayIndex,当arrayIndex的值等于点击选项卡的id,就给该选项卡active类名
html
<li v-for="(item,index) in list" :key="item.id"> //:key="item.id",确保选中准确性
<a href="#" :class="{active:item.id===arrayIndex}" @click="arrayIndex=item.id"> {{item.name}}</a>
</li>
javascript
const app = new Vue({ //创建vue实例
el: '#app', //选定容器
data: { //将定义的数据放入data中
list: [
{ id: 1, name: '京东秒杀' },
{ id: 2, name: '每日特价' },
{ id: 3, name: '品类秒杀' }
],
arrayIndex:2 //定义一个arrayIndex值
}
})
完整实例代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<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>
</head>
<body>
<div id="app">
<ul>
<li v-for="(item,index) in list" :key="item.id">
<a href="#" :class="{active:item.id===arrayIndex}" @click="arrayIndex=item.id">{{item.name}}</a>
</li>
</ul>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
list: [
{ id: 1, name: '京东秒杀' },
{ id: 2, name: '每日特价' },
{ id: 3, name: '品类秒杀' }
],
arrayIndex:2
}
})
</script>
</body>
</html>