Breadcrumb 实现

显示当前页面的路径,快速返回以前的任意页面。html

该组件的痛点在于:
  • 采用vnode设定扩展性较好的分隔符;
  • 利用vue-router高亮已选中的路径。

1. 实例

最终效果

代码vue

<!-- 基础用法 -->
<fat-breadcrumb separator="/" :paths="[ {name: '首页', to: '/'}, {name: '面包屑', to: '/Breadcrumb'}, {name: '标签页', to: '/Tabs'} ]" />

<!-- vnode分隔符 -->
/*
const _h = this.$createElement;
const separatorComponent = _h("fat-icon", {
    props: {
        name: "keyboard_arrow_right"
    }
});
*/
<fat-breadcrumb :separator-component="separatorComponent" :paths="[ { name: '首页', to: '/' }, { name: '面包屑', to: '/Breadcrumb' }, { name: '标签页', to: '/Tabs' } ]" />
复制代码

实例地址:Breadcrumb 实例node

代码地址:Github UI-Librarygit

2. 原理

因为分隔符要采用vnode的形式,因此该组件采用函数式来实现。其基本结构以下github

export default {
    functional: true,
    props: {
        paths: {
            type: Array,
            default: () => []
        },
        // String分隔符
        separator: {
            type: String,
            default: '/'
        },
        // Vnode分隔符
        separatorComponent: {
            type: Object
        }
    },
    render: function (_h, context) {
        ...
    }
}
复制代码

定义props中包含路径、分隔符,而后render function的实现为,vue-router

render: function (_h, context) {
    const {
        props: {
            paths,
            separator,
            separatorComponent
        }
    } = context
    // 遍历paths生成对应的child elements
    let elements = paths.map(path => {
        const {
            label,
            to
        } = path
        // 若是路径to存在,则利用router-link component
        const element = to ? 'router-link' : 'span'
        const props = to ? {
            to
        } : {}
        // return element vnode
        return _h(element, {
            'class': {
                'breadcrumb-item': true
            },
            props
        }, label)
    })

    return _h('div', {
        'class': {
            'breadcrumb': true
        }
    }, elements)
}
复制代码

利用vue-routeractive-classexact-active-class,来实现,游览过的路径高亮:api

  • active-class:连接激活时使用的 CSS 类名;
  • exact-active-class:连接被精确匹配的时候激活的 CSS 类名。

3. 使用

使用时,主要注意点是separatorComponent组件分隔符的构建,提供一种相对合理的方法,在Breadcrumb的父组件data中,完成vnode的建立工做。bash

data() {
    const _h = this.$createElement;

    return {
        separatorComponent: _h("fat-icon", {
            props: {
                name: "keyboard_arrow_right"
            }
        })
    }
}
复制代码

PS:此时data不能为箭头函数。函数

4. 总结

封装一个Breadcrumb组件,将vnode做为分隔符,方便其拓展。ui

原创声明: 该文章为原创文章,转载请注明出处。

相关文章
相关标签/搜索