Vue:Nav导航栏和标签页联动

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

一、Nav点击并将信息传递给对应的组件中

<template>
  <el-menu
      class="el-menu-vertical-demo"
      @open="handleOpen"
      @close="handleClose"
      style="height:100vh"
      background-color="#545c64"
      :default-active="activerouter"
      text-color="#fff"
      router 
      active-text-color="#ffd04b">
      <!-- 拉下菜单 -->
      <el-submenu v-for="(item , index) in navList"  :key="index" :index="item.id.toString()" v-if="item.children">
          <template slot="title">
            <i :class="item.icon"></i>
            <span >{{item.title}}</span>
          </template>
          <el-menu-item-group>
              <el-menu-item  @click="handelClickNacRouter(item)" v-for="(child , index) in item.children" :index="item.path"  >{{child.title}}</el-menu-item>
          </el-menu-item-group>
      </el-submenu>
      <!-- 点击菜单 -->
      <el-menu-item  :index="item.path" @click="handelClickNacRouter(item)" v-else >
        <i :class="item.icon"></i>
        <span slot="title" >{{item.title}}</span>
      </el-menu-item>
    </el-menu>
</template>
<script>
 export default {
  data(){
    return{
       navList:[
        {
          id:0,
          title:'首页',
          path:'/home',
          icon:'el-icon-house'
        },
        {
          id:1,
          title:'系统管理',
          icon:'el-icon-s-tools',
          permission_type:1,//下拉菜单
          children:[
            {
              id:101,
              title:'用户管理',
              permission_type:1,
              path:'/user',
            },
            {
              id:102,
              title:'客户管理',
              permission_type:1,
              path:'/role',
            },
          ]
        },
        {
          id:2,
          title:'磁盘管理',
          icon:'el-icon-receiving',
          permission_type:1,//下拉菜单
          children:[
            {
              id:201,
              title:'磁盘使用',
              permission_type:1,
              path:'/use',
            },
            {
              id:202,
              title:'磁盘剩余',
              permission_type:1,
              path:'/residue',
            },
          ]
        },
        {
          id:3,
          icon:'el-icon-brush',
          title:'图片生成',
          path:'/createimg'
        },

       ],
       //选中的nav菜单路由根据 在上方结构中 <el-menu-item :key="item.path"></el-menu-item> 根据定义的key值 和 activerouter的值相同就会显示此点击菜单高亮提示
       activerouter:null
    }
  },
  mounted(){
    //判断此变量是否为空,如果为空就代表第一次进入,请求Vuex中定义接收当前页面的变量。(保存的就是此页面的路径)
    if(this.activerouter === null){
       this.activerouter = this.$store.state.currentRouter
       //调用vuex中的muction方法,更改vuex中tabsList(tabs组件的值:表示标签页中改显示的内容,)
       this.$store.commit('addTabsList',this.navList[0])
    }
  },

  computed:{
    //计算Vuex中的当前路由的变量
    monitorCurrentRouter(){
      return this.$store.state.currentRouter
    },
  },
  watch:{
    //监听Vuex中当前路由的变化,如果此变量发生了变化,这边就可以拿到newVal最新的值,val是旧值
    monitorCurrentRouter(newVal,val){
        this.activerouter = newVal
    }
  },
  methods:{
    handleOpen(key, keyPath) {
        console.log(key, keyPath);
      },
      handleClose(key, keyPath) {
        console.log(key, keyPath);
      },
      //Nav组件点击菜单事件
      handelClickNacRouter(item){
        //调用Vuex中的同步方法,传递点击的菜单路由信息,更改Vuex中state的当前路由变量
        this.$store.commit('getCurrentRouter',item.path)
        //判断是session中保存的信息是否存在
        if(sessionStorage.getItem('TabsList') !== null ){
          //如果存在,表明已经不是第一次点击 判断点击的路由信息是否存在TabsList中,存在就不添加入session中
           let Tab = JSON.parse(sessionStorage.getItem('TabsList'))
           let list = []
           let ispush = true
            for(let i in Tab){
              if(Tab[i].id === item.id){
                ispush = false
                break;
              }
            }
            if(ispush){
              list = Tab.concat(item)
            }else{
              list = Tab
            }
            sessionStorage.setItem('TabsList',JSON.stringify(list) )  
          }else{
            //如果不存在就是把路由信息保存到回话中(seesion)
            let list = []
            list.push(item)
            sessionStorage.setItem('TabsList',JSON.stringify(list))  
          }
      },
  },
 }
</script>

<style scoped lang="less">
  /deep/.el-submenu__title{
    display: flex;
    padding-left: 30px !important;
    justify-content: start;
    align-items: center;
  }
  /deep/.el-menu-item{
    display: flex;
    padding-left: 30px !important;
    justify-content: start;
    align-items: center;
  }
  /deep/.el-submenu .el-menu-item{
    padding-left: 78px !important;
  }


</style>

二、Tabs标签页组件代码

<template>
   <div class="tabPage">
      <el-tabs class="tabs" v-model="editableTabsValue" @tab-click="TabsClickToGoPage" type="card" closable @tab-remove="removeTab">
        <el-tab-pane
          v-for="(item, index) in editableTabs"
          :key="item.id.toString()"
          :label="item.title"
          :name="item.id.toString()"
          :path ="item.path"
        >
        </el-tab-pane>
      </el-tabs>
   </div>
</template>

<script>
 export default {
  data(){
    return{
        editableTabsValue:'',
        editableTabs: [],
      }
  },
  mounted(){
    this.editableTabs = JSON.parse(sessionStorage.getItem('TabsList')) 
    //获取到tab所有的标签然后根据当前路由相比,渠道他们的id 将editableTabsValue的值和当前页面的id是一样的然后赋值,刷新页面自己选中当前也对应的tab
    this.currentPageRouter()
    //nav点击的时候绑定on 再次调用此方法
    this.$bus.$on('navClickTabs',()=>{
      this.currentPageRouter()
    })
  },  
  watch:{
      "editableTabs" (newTabs,Tabs){
        this.editableTabs = newTabs
      },
  },
  methods:{

    addTab(data) {
       this.editableTabs.push(data) 
        this.$store.commit('addTabsList',item) 
    },
    removeTab(targetName) {
        
    },

    //循环找出相同的值并返回
    forScanEqualValue(item){
      for(let i in this.editableTabs){
        if(item === this.editableTabs[i].path){
           return this.editableTabs[i].id + ''
        }
      }
    },

    //当前页面的路由信息
    currentPageRouter(){
      this.editableTabsValue = this.forScanEqualValue(this.$store.state.currentRouter)
    },
    //点击跳转页面
    TabsClickToGoPage(data){
      this.editableTabsValue = this.forScanEqualValue(data.$attrs.path)
      this.$router.push(data.$attrs.path)
    },
  }
 }
</script>
<style scoped lang="less">
.tabPage{
  width: 100%;
  height: 4vh;
}
</style>

3.Router文件

import Vue from 'vue'
import VueRouter from 'vue-router'
import Store from '../store'
import Bus from '../control/bus'

Vue.use(VueRouter)

 const originalPush = VueRouter.prototype.push;
 VueRouter.prototype.push = function push(location) {
   return originalPush.call(this, location).catch(err => err);
 }

const routes = [
  {
    path: '/login',
    name: 'login',
    component: () =>import('../views/login'),
  },
  {
    path: '/index',
    name: 'index',
    component: () =>
      import('../views/index'),
      children:[
          
          {
            path: '/createimg',
            name: 'createimg',
            component: () =>
              import('../views/createimg'),
          },
          {
            path: '/home',
            name: 'home',
            component: () =>
              import('../views/home'),
          },
      ]
    
  },
  {
      path: '/',
      redirect: '/login'
  },
  
 
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to,from,next)=>{
  //判断是否有登录
  if(localStorage.getItem('LoginUser')){
    if(to.path !== '/login') {
      //防止刷新时,nav组件丢失高亮问题 传递给vuex保存起来
      Store.commit('getCurrentRouter',to.path)
      console.log('Store.currentRouter',Store.state.currentRouter);
      Bus.$emit('navClickTabs')

      next()
      
    }else{
      next('/home')
    }
  }else{
    if(to.path !== '/login'){
      next('/login')
    }
    next()
  }
})


export default router




4.BUS总线程

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    currentRouter:null,//当前的路由信息
    //tabs组件的数据,点击的页面显示在tabs的组件上
    tabsList:[],

  },
  getters: {

    
  },
  mutations: {
    getCurrentRouter(state,path){
      state.currentRouter = path
    },

    addTabsList(state,data){
     if(state.tabsList.length !== 0){
          let  ispush = false
          if(state.tabsList.length !== 0){
            for (let i in state.tabsList){
                if(state.tabsList[i].path === data.path){
                  ispush = false
                  break;
                }else{  
                  ispush = true
                }
            }
          }else{
            ispush = true
          }
          if(ispush){
            state.tabsList.push(data)
          }
      }else{
        state.tabsList = data
      }
    },
  },
  actions: {
  },
  modules: {
  }
})

  • 6
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值