使用vue.js写一个tab选项卡效果

通常我们写tab选项卡的时候,一般都是用jq等去操作dom,给同级元素移除active类,然后,给被点击元素添加active类,但是在vue.js中,我们能不去操作dom我们就尽量不操作dom,那么该如何实现呢?

如果使用过vue-router,那么你会发现,vue-router在使用的时候其实就相当于一个tab选项卡,在点击之后,被点击的router-link元素会默认被添加上一个router-link-active的类,我们只需要设置这个类的样式即可.(当然,router-link-active)是vue-router默认的类名,你可以自己配置更改名称.这样我们可以直接使用vue的路由功能当tab选项卡使用了.那么如果不想用路由功能呢?

那么请看下面的方法:

html部分

<div> <ul> <li @click="toggle($index ,tab.view)" v-for="tab in tabs" :class="{active:active==$index}"> {{tab.type}} </li> </ul> <component :is="currentView"></component> </div>

js部分

Vue.component('child1', { template: "<p>this is child1</p>" }) Vue.component('child2', { template: "<p>this is child2</p>" }) new Vue({ el: "#app", data: { active: 0, currentView: 'child1', tabs: [ { type: 'tab1', view: 'child1' }, { type: 'tab2', view: 'child2' } ] }, methods: { toggle(i, v){ this.active = i this.currentView = v } } })

然后我们只需要设置一个.active的样式就可以了,比如设置一个最简单的

css

.active{ color:red }

简易的vue.js tab 选项卡

使用vue.js写一个tab选项卡效果

原理很简单,我们给tab选项绑定了toggle方法,点击时让active等于其index,从而给其添加了一个active类,而显示的内容也是同样的原理.比起传统操作dom方法,这个整体看上去更简洁,不过麻烦在每个tab选项卡都是一个组件.

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wwysfg.html