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

栏目: JavaScript · 发布时间: 7年前

内容简介:代码实例地址:Breadcrumb 实例代码地址:
从零实现Vue的组件库(五)- Breadcrumb 实现

代码

<!-- 基础用法 -->
<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-router active-class exact-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不能为箭头函数。


以上所述就是小编给大家介绍的《从零实现Vue的组件库(五)- Breadcrumb 实现》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

一站式学习C编程

一站式学习C编程

宋劲杉 / 电子工业出版社 / 2011-3 / 59.00元

《一站式学习c编程》有两条线索,一条线索是以linux平台为载体全面深入地介绍c语言的语法和程序的工作原理,另一条线索是介绍程序设计的基本思想和开发调试方法。本书分为两部分:第一部分讲解编程语言和程序设计的基本思想方法,让读者从概念上认识c语言;第二部分结合操作系统和体系结构的知识讲解程序的工作原理,让读者从本质上认识c语言。 《一站式学习c编程》适合做零基础的初学者学习c语言的第一本教材,......一起来看看 《一站式学习C编程》 这本书的介绍吧!

随机密码生成器
随机密码生成器

多种字符组合密码

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具