https://www.jb51.net/article/166102.htm
https://segmentfault.com/q/1010000012863019/
v-bind 三元:<h2 :class="off ? 'red':'green'">三元表达式</h2>
<!--这里是html结构-->
<div id="app">
<ul>
<li
v-for="(item,index) in tabs"
:class="{active:index == num}"
@click="tab(index)">{{item}}</li>
</ul>
<div class="tabCon">
<div
v-for='(itemCon,index) in tabContents'
v-show=" index == num">{{itemCon}}</div>
</div>
</div>
<!--这里是js代码-->
<script type="text/javascript">
var vm = new Vue({
el: '#app',
data: {
tabs: ["标题一", "标题二","标题三"],
tabContents: ["内容一", "内容二","内容三"],
num: 1
},
methods: {
tab(index) {
this.num = index;
}
}
});
</script>
先使用v-for把数据遍历渲染到页面上,v-for中有一个index表示索引,
将index作为参数传入到tab(index)这个函数中,
在data中定义一个num变量,在title中如果index==num,
这个title就会添加一个acive的class。
当然,这个num是需要在tab()这个函数中不断改变的,
需要将传入的索引值赋值给num,
这样在.tabCon里,我们就可以用v-show做下判断。v-show=”index==num”,
如果等于的话,当前的内容就会显示。否则隐藏。
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<style>
.box {
margin: 100px auto 0;
width: 80%;
}
.clear:after {
content: '';
display: block;
clear: both;
}
.tab {
width: 600px;
border: 1px solid #dcdfe6;
box-shadow: 0 2px 4px 0 rgba(0,0,0,.2);
}
ul {
margin: 0;
padding: 0;
list-style: none;
background: #f5f7fa;
border-bottom: 1px solid #e4e7ed;
position: relative;
}
li {
float: left;
padding: 0 20px;
margin: 0 0 -1px -1px;
position: relative;
height: 40px;
border: 1px solid transparent;
line-height: 40px;
cursor: pointer;
transition: .2s all;
}
li:hover {
color: rgb(64, 158, 255);
}
li.active {
background: #fff;
border-right-color: #dcdfe6;
border-left-color: #dcdfe6;
color: rgb(64, 158, 255);
}
.tab .content {
padding: 10px;
}
</style>
</head>
<body>
<div class="box">
<div class="tab">
<ul class="clear">
<!-- <li class="active">北京</li> -->
<li
v-for="item,index of items"
:class="{active:index == n}"
@click="tap(index)"
>
{{item.title}}
</li>
</ul>
<div class="content">
<p>{{items[n].content}}</p>
</div>
</div>
</div>
<script>
new Vue({
el:'.box',
data:{
items:[
{title:'北京',content:'这里是北京'},
{title:'上海',content:'这里是上海'},
{title:'广州',content:'这里是广州'},
{title:'深圳',content:'这里是深圳'},
{title:'武汉',content:'这里是武汉'}
],
n:0
},
methods: {
tap(i){
this.n = i
}
},
})
</script>
来源:CSDN
作者:loverxy丶Du
链接:https://blog.csdn.net/a772116804/article/details/86500049