美文网首页技术文档Web前端之路
使用vue.js写一个tab选项卡

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

作者: 勇PAN高峰 | 来源:发表于2016-12-22 14:04 被阅读10417次

通常我们写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 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  
  } 
 }
})

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

.active{
  color:red
}
简易的vue.js tab 选项卡
  原理很简单,我们给tab选项绑定了toggle方法,点击时让active等于其index,从而给其添加了一个active类,而显示的内容也是同样的原理.比起传统操作dom方法,这个整体看上去更简洁,不过麻烦在每个tab选项卡都是一个组件.
原文链接:[http://www.noob6.com/archives/14]

相关文章

网友评论

  • 梁同学de自言自语:如果child1实例,需要打开多个Tab页,是不是不能用vue `:is`属性了?
  • c714454862d0:我实现了tab卡用数据绑定,很简单的
    <div id="tab">
    <ul>
    <li v-for="(item,index) in items" @click="toggle(index,item.view)" :class="{active:active==index}">{{item.text}}</li>
    </ul>
    <div>
    {{contents[active].text}}
    </div>
    <!-- <component :is="currentView"></component> -->
    </div>
    var tab = new Vue({
    el:'#tab',
    data: {
    active: 0,
    currentView: 'child1',
    items:[
    {text: '首页',view:'child1'},
    {text: '产品',view:'child2'},
    {text: '资料',view:'child3'}
    ],
    contents:[
    {text:'this is child1'},
    {text:'this is child2'},
    {text:'this is child3'},
    ]
    },
    methods:{
    toggle(i,v){
    this.active = i
    this.currentView = v

    console.log(this.currentView)
    }
    }


    })
    勇PAN高峰:@cd57558cd2be :看看html结构里面的:class="{active:active==$index}",点击之后 this.active = i ,这个是当data里面的active变量等于自身的index的时候,就会被添加上active类
    cd57558cd2be:请问,点击当前选项卡添加active,另一个选项卡active样式清除应该怎么改?
    朵霞:看不懂

本文标题:使用vue.js写一个tab选项卡

本文链接:https://www.haomeiwen.com/subject/fcoxvttx.html