1、实现tab切换就是 单击一个选项卡显示其对应的内容,且被点击的选项卡改变颜色,下面有两种实现方法(都不要忘了vue.js的目录要写正确)
2、第一种方法效果图
这个没什么可说的,直接看代码吧(两种方式)
2、第一种完整代码(下边这段代码是我在网上学的)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="./vue.js"></script>
<style>
button {
width: 40px;
height: 30px;
text-align: center;
border: none;
cursor: pointer;
}
.active {
background: red;
color: #fff;
border: none;
}
* {
margin: 0;
padding: 0;
list-style: none;
}
#app {
width: 600px;
height: 600px;
border: 1px solid #b3b3b3;
margin: auto;
}
ul {
height: 50px;
background-color: #b6b6b6;
color: #000;
display: flex;
justify-content: space-between;
align-items: center;
}
ul li {
width: 150px;
text-align: center;
line-height: 50px;
font-size: 18px;
}
#app div {
padding: 10px;
font-size: 18px;
}
.active {
background-color: #00557F;
color: #fff;
}
</style>
</head>
<body>
<div id="app">
<ul>
<li v-for="(val,index) in item" @click="changes(index)" :class="{active:index == num}">{{item[index]}}
</li>
</ul>
<div v-for="(val,index) in cont" v-show="index==num">{{val}}</div>
</div>
<script>
/*
运用知识点:
v-for
v-on,简写@
v-bind简写:
v-show
思路:
循环数据,当点击时候,把key传到changes方法中,然后num赋值给active
循环数组,只要box中key等于num就让它显示出来
*/
new Vue({
el: '#app',
data: {
item: ["html", "css", "javascript", "Vue"], //导航栏标题
cont: ["html内容", "css内容", "javascript内容", "Vue内容"], //内容
num: 0
},
methods: {
changes(key) {
this.num = key;
}
}
});
</script>
</body>
</html>
3、第二种方式效果图
4、第二种方式完整代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="../vue.js"></script>
<style type="text/css">
.active{
color: firebrick;
}
</style>
</head>
<body>
<div id="app">
<!-- 根据num值来添加active class 注意active是用单引号包裹的 -->
<!-- 添加单击事件更改num的值 -->
<button :class="num==1?'active':''" @click="num=1">html</button>
<button :class="num==2?'active':''" @click="num=2">css</button>
<button :class="num==3?'active':''" @click="num=3">javascript</button>
<!-- 根据num动态切换显示div内容 -->
<div v-show="num==1">html内容</div>
<div v-show="num==2">css内容</div>
<div v-show="num==3">javascript内容</div>
</div>
<script type="text/javascript">
new Vue({
el:"#app",
data:{
// 当前索引(显示的索引,需要添加class的索引)
num:1,
},
})
</script>
</body>
</html>