import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const state = () => ({
tabMenu: [],
activeIndex: '/',
includePage: [],
})
const getters = {
}
const actions = {
}
const mutations = {
updateTabs (state, data) {
if (state.activeIndex === data.path) return
state.activeIndex = data.path
const isTab = state.tabMenu.some(item => item.path === data.path)
if (!isTab) {
state.tabMenu.push(data)
const activePage = data?.meta?.activePage || ''
state.includePage.push(activePage)
}
},
deleteTabs (state, path) {
const index = state.tabMenu.findIndex(item => item.path === path);
state.tabMenu.splice(index, 1)
state.includePage.splice(index, 1)
const href = state.tabMenu.at(-1).path
router.push(href)
},
initTabs (state) {
state.tabMenu = []
state.activeIndex = '/'
state.includePage = []
},
getRefreshTabs (state) {
const tab = { path: '/work', name: '工作台', meta: { activePage: 'Work' } }
state.tabMenu.push(tab)
state.includePage.push(tab.meta.activePage)
state.activeIndex = tab.path
router.push(tab.path)
},
}
export default new Vuex.Store({
state,
mutations
})
<el-tabs :value="activeIndex"
type="card"
closable
@tab-click="tabClick"
@tab-remove="tabRemove">
<el-tab-pane v-for="item in tabMenu"
:key="item.path"
:label="item.name"
:name="item.path">
</el-tab-pane>
</el-tabs>
<keep-alive :include="includePage">
<router-view></router-view>
</keep-alive>
methods: {
...mapMutations('tabs', ['updateTabs', 'deleteTabs', 'initTabs', 'getRefreshTabs']),
handleSelect (path, keyPath) {
console.log(path, keyPath)
this.$router.push(path)
},
tabClick (tab) {
this.$router.push(tab.name)
},
tabRemove (tab) {
if (tab === '/work') return
this.deleteTabs(tab)
},
},
computed: {
...mapState('tabs', ['tabMenu', 'includePage', 'activeIndex']),
},
watch: {
'$route' (to) {
this.updateTabs(to)
}
}
created () {
this.initTabs()
},
mounted () {
this.getRefreshTabs()
},
const router = new VueRouter({
routes = [
{
path: '/',
component: Home,
name: '导航一',
iconCls: 'el-icon-message',
children: [
{ path: '/main', component: Main, name: '主页', meta: { activePage: 'Main'}},
{ path: '/table', component: Table, name: 'Table', meta: { activePage: 'Table'} },
{ path: '/form', component: Form, name: 'Form', meta: { activePage: 'Form'} },
{ path: '/user', component: User, name: '列表', meta: { activePage: 'User'} },
]
}
]
})