详解使用详解使用vue实现实现tab 切换操作切换操作
主要介绍了详解使用vue实现tab操作,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编
过来看看吧
在使用jQuery类库实现tab功能时,是获取鼠标在mousenter或click时的index值,然后切换到当前的标题和内容,把其他的标
题和内容的状态去掉:
$('.tab .title').find('.item')
.removeClass('current').eq(index).addClass('current'); // 为index位置的title添加current
$('.tab .content').find('.item')
.hide().eq(index).show(); // 显示index位置的内容
那么在使用vue实现tab功能时,就不是像jQuery这种直接操作DOM了。我这里总结了下实现tab功能的3个思路,仅供参考。
1. 切换切换content或者直接切换内容或者直接切换内容
这种思路下,我们首先把结构搭建起来,然后用一个变量selected表示tab当前展示的位置,给li标签添加mouseenter或click事
件,将当前的index传递进去:
html代码:
<div class="hd">
<ul class="clearfix">
<li v-for="(item, index) of list" :class="{active:selected==index}" @mouseenter="change(index)">{{item.title}}</li>
</ul>
</div>
<div v-for="(item, index) of list" :class="{active:selected==index, item:true}" v-html="item.content"></div>
js代码:
var app = new Vue({
el: '#app',
data: {
selected: 0, //当前位置
list: [
{
title: '11111',
content: '11111content'
},
{
title: '22222',
content: '222222content'
},
{
title: '33333',
content: `<div>
<span style="color:#f00">hello world</span>
<p><input type="text" v-model="message"></p>
<p>{{message}}</p>
</div>`
}
]
},
methods: {
change(index) {
this.selected = index;
}
}
})
绑定的change(index)事件,每次都将index给了selected,然后tab就会切换到对应的标签。
上面的代码里,我们是通过切换div的显示与隐藏来进行执行的。tab中的content里如果只有纯html内容,我们可以直接
把list[selected].content展示到.bd中:
<div class='bd' v-html="list[selected].content"></div>
每次selected变换时,bd的内容都会发生变化。
2. 使用使用currentView
在上面的实现方式中,第3个tab里有个输入框与p标签双向绑定,但是没有效果,因为vue是把list中的内容作为html元素填充
到页面中的,message并没有作为vue的属性绑定给input。那么使用组建和currentView就能弥补这个缺陷。
- 1
- 2
前往页