- 安装依赖引用依赖
/* 安装依赖 */ // 安装element-ui npm i element-ui -S // 安装vue-fragment npm i -s vue-fragment /* main.js 引入 */ import Vue from 'vue'; // 引用element-ui import ElementUI from 'element-ui'; import 'element-ui/lib/theme-chalk/index.css'; // 引用vue-fragment import { Plugin } from 'vue-fragment' Vue.use(Plugin)
- SidebarItem 组件封装
<template> <fragment v-if="!item.hidden"> <el-submenu v-if="item.children && item.children.length" :index="item.label" > <template slot="title"> <i :class="item.icon"/> {{ item.label }} </template> <sidebar-item v-for="child in item.children" @item-click="(i) => $emit('item-click', i)" :key="child.path" :item="child" /> </el-submenu> <el-menu-item v-else :index="item.url" @click="$emit('item-click', item)"> <i :class="item.icon"/> {{ item.label }} </el-menu-item> </fragment> </template> <script> export default { name: 'SidebarItem', props: { item: { type: Object, required: true } }, methods: { handleItemClick (item) { this.$emit('item-click', item) } } } </script>
- SidebarItem组件应用
<template> <el-menu :default-active="activeIndex" unique-opened @select="handleLoadUrl"> <sidebar-item v-for="item in menuList" :key="item.path" :item="item" @item-click="handleItemClick"/> </el-menu> </template> <script> import SidebarItem from './sidebarItem.vue' export default { components: { SidebarItem }, data () { return { activeIndex: '/1', menuList: [ { label: '一级菜单1', icon: 'el-icon-s-help', url: '/1' }, { label: '一级菜单2', icon: 'el-icon-s-help', url: '/2' children: [ { label: '二级菜单2.1', url: '/2/1' } ] } ] } }, watch: { $route: { handler: function (to, from) { this.$nextTick(() => { if (to) { this.activeIndex = to.path } }) // console.log(to, from) }, immediate: true } }, created () { }, mounted () {}, methods: { handleLoadUrl (index, indexPath) { // console.log(index, indexPath, 5566) }, handleItemClick (item) { const { url, label } = item this.activeIndex = url || label this.$router.push(this.activeIndex) } } } </script>
- .....