该组件的痛点在于:显示当前页面的路径,快速返回以前的任意页面。html
vnode
设定扩展性较好的分隔符;vue-router
高亮已选中的路径。代码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
因为分隔符要采用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-router
的active-class
,exact-active-class
,来实现,游览过的路径高亮:api
使用时,主要注意点是separatorComponent
组件分隔符的构建,提供一种相对合理的方法,在Breadcrumb的父组件data
中,完成vnode
的建立工做。bash
data() {
const _h = this.$createElement;
return {
separatorComponent: _h("fat-icon", {
props: {
name: "keyboard_arrow_right"
}
})
}
}
复制代码
PS:此时data不能为箭头函数。函数
封装一个Breadcrumb组件,将vnode
做为分隔符,方便其拓展。ui
原创声明: 该文章为原创文章,转载请注明出处。