Vue.js組件實現選項卡以及切換動畫特效,供大家參考,具體內容如下
最近在學習Vue,當看梁灝大神寫的《Vue.js實戰》時看到了關于用組件實現選項卡功能,我也根據課后的練習加上自己的理解重新編寫了一下。
組件分為pane.js和tabs.js兩個部分,話不多說,直接上代碼。
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="style.css" rel="external nofollow" > <title>Document</title></head><body> <div id="app"> <tabs v-model="activeKey"> //transiton是Vue自帶封裝的,不懂的同學可以去找文檔,主要是可以實現動畫 <transition name="slide-fade"> <pane label="標簽一" name="1"> 標簽一的內容 </pane> </transition> <transition name="slide-fade"> <pane label=" 標簽二" name="2"> 標簽二的內容 </pane> </transition> <transition name="slide-fade"> <pane label="標簽三" name="3"> 標簽三的內容 </pane> </transition> </tabs> </div> <script src="vue/vue.js"></script> <script src="pane.js"></script> <script src="tabs.js"></script> <script src="text.js"></script></body></html>
//tabs.jsVue.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> <button @click="removePane()"> 關閉/打開 </button> </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, }, ]; }, getTabs() { return this.$children.filter(function (item) { return item.$options.name === 'pane'; }); }, updateNav() { this.navList = []; var _this = this; this.getTabs().forEach(function (pane, index) { _this.navList.push({ label: pane.label, name: pane.name || index, bool: pane.closable, }); 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); }, removePane: function () { var bool = this.navList[1].bool; console.log(bool); if (bool) { this.navList[1].bool = false; this.currentValue = '0'; } if (!bool) { this.navList[1].bool = true; this.currentValue = '1'; this.$emit('input', '1'); } }, }, watch: { value: function (val) { this.currentValue = val; }, currentValue: function () { console.log('demo'); this.updateStatus(); }, },});
新聞熱點
疑難解答
圖片精選