从零实现Vue的组件库(五)- Breadcrumb 实现
栏目: JavaScript · 发布时间: 7年前
内容简介:代码实例地址: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 实现》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Designing Data-Intensive Applications
Martin Kleppmann / O'Reilly Media / 2017-4-2 / USD 44.99
Data is at the center of many challenges in system design today. Difficult issues need to be figured out, such as scalability, consistency, reliability, efficiency, and maintainability. In addition, w......一起来看看 《Designing Data-Intensive Applications》 这本书的介绍吧!