Vue实现选项卡切换,tab切换

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>

  • 23
    点赞
  • 87
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值