如何实现Vue+ Element点击左侧,上面出现动态标签页 左侧index为路径,
时间: 2023-05-24 19:04:14 浏览: 203
您可以使用Vue.js 和 Element组件库来实现此功能。下面是实现此功能的简要步骤:
1. 在main.js文件中引入Vue.js 和 Element组件库,并创建Vue.js实例:
```
import Vue from 'vue'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import App from './App.vue'
Vue.use(ElementUI)
new Vue({
el: '#app',
render: h => h(App)
})
```
2. 在App.vue组件中,使用el-menu和el-tabs组件来实现左侧菜单和标签页:
```
<template>
<div id="app">
<el-row>
<el-col :span="6">
<el-menu
:default-active="$route.path"
mode="vertical"
router>
<el-menu-item
v-for="item in menuList"
:key="item.path"
:index="item.path">
<i :class="item.icon"></i>
{{ item.name }}
</el-menu-item>
</el-menu>
</el-col>
<el-col :span="18">
<el-tabs v-model="activeTabName" closable>
<el-tab-pane
v-for="item in tabList"
:key="item.path"
:label="item.label"
:name="item.path">
<router-view></router-view>
</el-tab-pane>
</el-tabs>
</el-col>
</el-row>
</div>
</template>
<script>
export default {
data() {
return {
menuList: [
{ name: '首页', path: '/', icon: 'el-icon-s-home' },
{ name: '用户列表', path: '/users', icon: 'el-icon-user' },
{ name: '商品列表', path: '/products', icon: 'el-icon-goods' },
],
tabList: [],
activeTabName: '/'
}
},
watch: {
'$route.path'(newVal, oldVal) {
if (newVal !== oldVal) {
this.addTab(newVal)
}
}
},
methods: {
addTab(path) {
const item = this.tabList.find(item => item.path === path)
if (!item) {
const name = this.menuList.find(item => item.path === path)?.name ?? '未知页面'
this.tabList.push({ path, label: name })
}
this.activeTabName = path
}
}
}
</script>
```
3. 在路由文件中配置路由。
```
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import Users from '../views/Users.vue'
import Products from '../views/Products.vue'
Vue.use(VueRouter)
const routes = [
{ path: '/', component: Home },
{ path: '/users', component: Users },
{ path: '/products', component: Products },
]
export default new VueRouter({
mode: 'history',
routes
})
```
这样就可以实现点击左侧菜单项时,在上方动态添加相应的标签页,并在标签页之间实现切换。
阅读全文