网络编程 发布日期:2025/11/11 浏览次数:1
通常我们写tab选项卡的时候,一般都是用jq等去操作dom,给同级元素移除active类,然后,给被点击元素添加active类,但是在vue.js中,我们能不去操作dom我们就尽量不操作dom,那么该如何实现呢"htmlcode">
<div id="app">
<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 选项卡
原理很简单,我们给tab选项绑定了toggle方法,点击时让active等于其index,从而给其添加了一个active类,而显示的内容也是同样的原理.比起传统操作dom方法,这个整体看上去更简洁,不过麻烦在每个tab选项卡都是一个组件.
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。