封装一个简化版的面包屑组件

直接上组件代码:

<template>
    <div>
        <el-breadcrumb separator=">">
            <el-breadcrumb-item v-for="item in levelList" :key="item.path">
                <span @click.prevent="handleLink(item)" style="cursor:pointer;">{{ item.meta.title }}</span>
            </el-breadcrumb-item>
        </el-breadcrumb>
    </div>
</template>

<script>
export default {
    data(){
        return {
            leavelList:null,
        }
    },
    watch: {
        $route(route) {
            this.getLeavelList();
        }
    },
    created(){
        this.getLeavelList()
    },
    methods:{
        getLeavelList(){
            var matched=this.$route.matched.filter(item => item.meta && item.meta.title);
            const first = matched[0];
            if (!this.isDashboard(first)) {
                matched = [{ name: '/dashboard', meta: { title: 'Dashboard' }}].concat(matched)
            };
            this.levelList = matched;
        },
        isDashboard(route) {//判断是不是首页
            const name = route && route.name
            if (!name) {
                return false
            }
            return name.trim().toLocaleLowerCase() === 'Dashboard'.toLocaleLowerCase()
        },
        handleLink(item) {
            const { name } = item;
            if(name==='/dashboard'){//因为首页name是一个路径所以判断如果是首页就用路径的方式跳转
                this.$router.push({path:name})
                return;
            }
            this.$router.push({name:name})
        }
    }
}
</script>

<style>
</style>

引入方式:

引入:

import TestBreadcrumb from "@/components/testBreadcrumb";

注册子组件:

components:{
    TestBreadcrumb
  },

页面使用:

<TestBreadcrumb></TestBreadcrumb>

声明:

这个组件对路由有要求,路由配置中要有meta路由元信息

像这样:

{
        path: 'tree',
        name: 'Tree',
        component: () => import('@/views/tree/index'),
        meta: { title: 'Tree', icon: 'tree' }
      }

猜你喜欢

转载自www.cnblogs.com/fqh123/p/11334652.html
今日推荐