element UI中的tab切换栏

html代码:(用的是el-tab组件)

 <el-tabs v-model="activeIndex" type="border-card" @tab-click="tabClick" @tab-remove="tabRemove">
<el-tab-pane :closable="item.name == '首页'?false:true" :key="item.name" v-for="(item) in options" :label="item.name" :name="item.route">
</el-tab-pane>
</el-tabs>

methods:

  // tab 切换时, 动态的切换路由
tabClick(tab) {
this.$router.push({
path: this.activeIndex
}); // 路由跳转
}, tabRemove(targetName) {
this.$store.dispatch('menu/deleteTabs', targetName);
// 还同时需要处理一种情况当需要移除的页面为当前激活的页面时, 将上一个 tab 页作为激活 tab
if (this.activeIndex === targetName) {
// 设置当前激活的路由
if (this.options && this.options.length >= ) {
this.$store.dispatch('menu/setActiveIndex', this.options[this.options.length - ].route);
this.$router.push({
path: this.activeIndex
});
}else{
this.$router.push('/home')
}
}
}

数据是存放在vuex中的:

 computed: {
options: {
get () {return this.$store.state.menu.options},
set (val) {this.$store.dispatch('menu/addTabs', val)}
},
// 动态设置及获取当前激活的 tab 页
activeIndex: {
get() {
return this.$store.state.menu.activeIndex;
},
set(val) {
this.$store.dispatch('menu/setActiveIndex', val);
}
}
},

mounted:

 mounted() {
let options = JSON.parse(window.localStorage.getItem('menuOptions'))
this.activeIndex = localStorage.getItem('menuIndex')
if(!options) {
options = []
this.$router.push('/home')
this.$store.commit('menu/SET_ACTIVEI_NDEX', options.route)
// this.$store.dispatch('menu/setActiveIndex', options.route)
}else {
this.$store.commit('menu/SET_OPTIONS', options)
}
//this.$store.dispatch('menu/setActiveIndex', options.route)
//this.$store.commit('menu/SET_OPTIONS', options)
// 设置当前激活的路由
if (options && options.length >= ) {
for(var i = ; i < options.length; i++){
if(options[i].route == this.activeIndex){
this.$store.dispatch('menu/setActiveIndex', options[i].route) }
}
}else{
this.$router.push('/home')
}
},

store/menu.js

 const state = {
options: [{ route: '/home', name: '首页' }],
activeIndex: '/home'
}
const mutations = {
SET_OPTIONS: (state, data) => {
state.options = data
},
// 添加 tabs
ADD_TABS: (state, data) => {
//state.options.findIndex(m => m.name === data.name) < 0 && state.options.push(data)
state.options.push(data);
localStorage.setItem("menuOptions", JSON.stringify(state.options))
},
// 删除 tabs
DELETE_TABS: (state, route) => {
let index = ;
for (let option of state.options) {
if (option.route === route) {
break;
}
index++;
}
state.options.splice(index, );
localStorage.setItem("menuOptions", JSON.stringify(state.options))
},
// 设置当前激活的 tab,route
SET_ACTIVEI_NDEX: (state, index) => {
state.activeIndex = index;
localStorage.setItem("menuIndex", state.activeIndex)
},
}
const actions = {
addTabs({ commit }, info) {
commit('ADD_TABS', info)
},
deleteTabs({ commit }, info) {
commit('DELETE_TABS', info)
},
setActiveIndex({ commit }, info) {
commit('SET_ACTIVEI_NDEX', info)
},
} export default {
namespaced: true,
state,
mutations,
actions
}

over!

上一篇:初试 Kubernetes 集群中使用 Traefik 反向代理


下一篇:CentOS 下JDK安装