import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const state = () => ({
options: [],
activeIndex: '/',
includePage: [],
})
const getters = {
}
const actions = {
}
const mutations = {
addTabs (state, data) {
state.options.push(data)
state.activeIndex = data.href
const reg = /\/(\w+)$/
const match = reg.exec(data.href)
match[1] ? state.includePage.push(match[1]) : ''
},
deleteTabs (state, path) {
const index = state.options.findIndex(item => item.href === path);
state.options.splice(index, 1)
state.includePage.splice(index, 1)
const href = state.options.at(-1).href
state.activeIndex = href
router.push(href)
},
setActiveIndex (state, index) {
if (state.activeIndex === index) return
state.activeIndex = index
router.push(index)
},
initTabs (state) {
state.options = []
state.activeIndex = '/'
state.includePage = []
},
getRefreshTabs (state) {
const obj = { href: '/Main', title: '主页' }
state.options.push(obj)
state.includePage.push('Main')
state.activeIndex = '/Main'
router.push('/Main')
},
}
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 options"
:key="item.href"
:label="item.title"
:name="item.href">
</el-tab-pane>
</el-tabs>
<keep-alive :include="includePage">
router-view></router-view>
</keep-alive>
methods: {
...mapMutations('tabs', ['addTabs', 'deleteTabs', 'setActiveIndex', 'initTabs',]),
handleSelect (path, keyPath) {
console.log(path, keyPath)
const isHref = this.options.some(item => item.href === path)
const data = this.menus.find(item => item.href === path)
this.$router.push(data.href)
isHref ? this.setActiveIndex(path) : this.addTabs(data)
},
tabClick (tab) {
this.setActiveIndex(tab.name)
},
tabRemove (tab) {
if (tab === '/Main') return
this.deleteTabs(tab)
},
},
computed: {
...mapState('tabs', ['options', 'includePage', 'activeIndex']),
},
watch: {
'$route' (to) {
let { name, path } = to
const isHref = this.options.some(item => item.href === path)
let data = { title: name, href: path }
isHref ? this.setActiveIndex(path) : this.addTabs(data)
}
}
created () {
this.initTabs()
},
const router = new VueRouter({
routes = [
{
path: '/',
component: Home,
name: '导航一',
iconCls: 'el-icon-message',
children: [
{ path: '/main', component: Main, name: '主页', hidden: true },
{ path: '/table', component: Table, name: 'Table', meta: { keepAlive: false} },
{ path: '/form', component: Form, name: 'Form', meta: { keepAlive: true} },
{ path: '/user', component: user, name: '列表' },
]
}
]
})