通常我們寫tab選項(xiàng)卡的時(shí)候,一般都是用jq等去操作dom,給同級(jí)元素移除active類,然后,給被點(diǎn)擊元素添加active類,但是在vue.js中,我們能不去操作dom我們就盡量不操作dom,那么該如何實(shí)現(xiàn)呢?
如果使用過vue-router,那么你會(huì)發(fā)現(xiàn),vue-router在使用的時(shí)候其實(shí)就相當(dāng)于一個(gè)tab選項(xiàng)卡,在點(diǎn)擊之后,被點(diǎn)擊的router-link元素會(huì)默認(rèn)被添加上一個(gè)router-link-active的類,我們只需要設(shè)置這個(gè)類的樣式即可.(當(dāng)然,router-link-active)是vue-router默認(rèn)的類名,你可以自己配置更改名稱.這樣我們可以直接使用vue的路由功能當(dāng)tab選項(xiàng)卡使用了.那么如果不想用路由功能呢?
那么請(qǐng)看下面的方法:
html部分
<div id="app">
<ul>
<li @click="toggle(index ,tab.view)" v-for="(tab,index) 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
}
}
})
然后我們只需要設(shè)置一個(gè).active的樣式就可以了,比如設(shè)置一個(gè)最簡(jiǎn)單的
css
.active{
color:red
}
簡(jiǎn)易的vue.js tab 選項(xiàng)卡
原理很簡(jiǎn)單,我們給tab選項(xiàng)綁定了toggle方法,點(diǎn)擊時(shí)讓active等于其index,從而給其添加了一個(gè)active類,而顯示的內(nèi)容也是同樣的原理.比起傳統(tǒng)操作dom方法熙暴,這個(gè)整體看上去更簡(jiǎn)潔,不過麻煩在每個(gè)tab選項(xiàng)卡都是一個(gè)組件.
原文鏈接:[http://www.noob6.com/archives/14]