Vue学习笔记——选项卡案例(tab栏切换)
内容截图:
常犯问题:看到这个内容的时候,总是思考怎么将3个div叠起来。 其实不需要,隐藏了div不占位置的。每次只显示一个div且显示时占的位置是一样的 如果你都没有给它们添加显示的类,那么你只能看到选项,看不到图的盒子 … .tab ul li.active{ //这里的.不可以分开的,分开就看不到样式了 background-color: orange; }
框架:
ul 中 li 代表每一项的tab栏div 代表每个对应的盒子
如何将data中的数据渲染到页面上?
利用v-for="(item,index) in list"然后把list中的数据渲染到页面中 {{item.title}}
如何设置点击选中的背景?
让默认的第一项tab栏高亮在data中定义一个默认的索引 currentIndex 为0给第一个li 添加active 类名 通过v-bind:class=" "currentIndex===index 如果相等,则添加类名active类名,否则添加 空类名
图片显示同上👆
步骤:
1. 将写si的数据改成动态的
2. 添加点击事件
代码:
<!DOCTYPE html
>
<html
>
<head
>
<meta charset
="utf-8">
<title
>选项卡
</title
>
<style type
="text/css">
.tab ul
{
overflow
: hidden
;
padding
: 0;
margin
: 0;
}
.tab ul li
{
box
-sizing
: border
-box
;
padding
: 0;
float
: left
;
width
: 100px
;
height
: 45px
;
line
-height
: 45px
;
list
-style
: none
;
text
-align
: center
;
border
-top
: 1px solid blue
;
border
-right
: 1px solid blue
;
cursor
}
.tab ul li
:first
-child
{
border
-left
: 1px solid blue
;
}
.tab ul li
.active
{
background
-color
: orange
;
}
.tab div
{
width
: 500px
;
height
: 300px
;
display
: none
;
text
-align
: center
;
font
-size
: 30px
;
line
-height
: 300px
;
border
:1px solid blue
;
border
-top
:0px
;
}
.tab div
.current
{
display
: block
;
}
</style
>
</head
>
<body
>
<div id
="app">
<div
class="tab">
<ul
>
<li
:key
="item.id" v
-for="(item,index) in list" v
-on
:click
="handle(index)" :class='currentIndex==index?"active":""'>{{item
.title
}}</li
>
</ul
>
<div
:key
="item.id" v
-for="(item,index) in list" :class='currentIndex==index?"current":""'>
<img
:src
="item.path">
</div
>
</div
>
</div
>
<script src
="js/vue.js"></script
>
<script type
="text/javascript">
var vm
= new Vue({
el
:'#app',
data
:{
list
: [{
id
: 1,
title
: 'apple',
path
: 'img/apple.png'
},{
id
: 2,
title
: 'orange',
path
: 'img/orange.png'
},{
id
: 3,
title
: 'lemon',
path
: 'img/lemon.png'
}],
currentIndex
:0
},
methods
:{
handle
:function(index
){
this.currentIndex
= index
;
console
.log(this.currentIndex
);
}
}
})
</script
>
</body
>
</html
>