vue选项卡组件
GlimmerL 人气:0主要功能:点击不同的选项,显示不同的内容
html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <link rel="stylesheet" type="text/css" href="css/style.css" /> <script src="js/jquery.js" type="text/javascript" charset="utf-8"></script> <script src="js/vue.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript"> $(document).ready(function(){ var app=new Vue({ el: "#app", data: { activeKey: '1'//被选择的选项 } }); }); </script> </head> <body> <div id="app" v-cloak> <tabs v-model="activeKey"> <pane label="一" name="1">我是张三</pane> <pane label="二" name="2">我是李四</pane> <pane label="三" name="3">我是牛五</pane> </tabs> </div> <script src="js/pane.js" type="text/javascript" charset="utf-8"></script> <script src="js/tabs.js" type="text/javascript" charset="utf-8"></script> </body> </html>
pane.js
Vue.component('pane',{ name: 'pane', template: '\ <div class="pane" v-show="show"> \ <slot></slot> \ </div>', data: function(){ return { show: true } }, props: { name: { type: String }, label: { type: String, default: '' } }, methods: { updateNav() { this.$parent.updateNav(); } }, watch: { label(){ this.updateNav(); } }, mounted() { this.updateNav(); } })
tabs.js
Vue.component('tabs',{ template: '\ <div class="tabs">\ <div class="tabs-bar">\ <div \ :class="tabCls(item)" \ v-for="(item,index) in navList" \ @click="handleChange(index)"> \ {{item.label}} \ </div>\ </div> \ <div class="tabs-content"> \ <slot></slot> \ </div> \ </div>', props: { value: { type: [String,Number] } }, data: function(){ return { currentValue: this.value, navList: [] } }, methods: { tabCls: function(item){ return [ 'tabs-tab', { 'tabs-tab-active': item.name===this.currentValue } ] }, //遍历所有为pane的子元素 getTabs(){ return this.$children.filter(function(item){ return item.$options.name==='pane'; }); }, //将pane子元素中label name放进navList数组 updateNav() { this.navList=[]; var _this=this; this.getTabs().forEach(function(pane,index){ _this.navList.push({ label: pane.label, name: pane.name ||index }); if(!pane.name) pane.name=index; if(index===0){ if(!_this.currentValue){ _this.currentValue=pane.name || index; } } }); this.updateStatus(); }, updateStatus(){ var tabs=this.getTabs(); var _this=this; //显示当前正在选中的 tabs.forEach(function(tab){ return tab.show=tab.name===_this.currentValue; }) }, handleChange: function(index){ var nav =this.navList[index]; var name=nav.name; this.currentValue=name; this.$emit('input',name); this.$emit('on-click',name); } }, watch: { value: function(val){ this.currentValue=val; }, currentValue: function (){ this.updateStatus(); } } })
加载全部内容