从零实现Vue的组件库(五)- Breadcrumb 实现

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

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

1. 实例

最终效果

代码

<!-- 基础用法 -->
<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 实例

代码地址:Github UI-Library

2. 原理

由于分隔符要采用vnode的形式,所以该组件采用函数式来实现。其基本结构如下

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的实现为,

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,来实现,游览过的路径高亮:

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

3. 使用

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

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

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

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

4. 总结

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

往期文章:

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

猜你喜欢

转载自juejin.im/post/5c22df8b5188253ff14792b3