使用场景:点击资源列表中的某一行,可以跳转到该行详情,涉及层级关系,考虑用面包屑导航,为了防止面包屑导航在页面刷新时不存在,考虑监听路由参数的变化
分析:假设面包屑导航的名字为 :全部 > test1 > test2
全部对应的路由参数为 /
test1 对应的路由参数为 /test1
test2 对应的路由参数为 /test1/test2
结论:面包屑的名字根据 路由查询参数.split(‘/’)分割的数组获取
面包屑的 :to
导航把面包屑的名字按 .join(‘/’) 拼接起来
防止刷新页面丢失面包屑,需要根据路由参数获取面包屑的名字
代码部分
template部分
<el-breadcrumb separator=">">
<template v-for="(item, index) in breadcrumb">
<el-breadcrumb-item v-if="index < (breadcrumb.length - 1)" :key="index" :to="{ path: '/info/resource', query: { path: setQueryPath(index) } }">{{ item }}</el-breadcrumb-item>
<el-breadcrumb-item v-else :key="index">{{ item }}</el-breadcrumb-item>
</template>
<el-breadcrumb-item v-if="breadcrumb.length === 1"></el-breadcrumb-item>
</el-breadcrumb>
js部分
data () {
return {
breadcrumb: [],
}
},
created () {
this.getList()
if (this.$route.query.path === undefined || this.$route.query.path === '/') {
this.breadcrumb = ['我的资源']
} else {
this.breadcrumb = [...['我的资源'], ...this.$route.query.path.split('/').slice(1)]
}
},
watch: {
$route (val) { // 监听路由参数变化
if (val.query.path === undefined || val.query.path === '/') {
this.list.filters.path = '/'
this.breadcrumb = ['我的资源']
} else {
this.list.filters.path = val.query.path
this.breadcrumb = [...['我的资源'], ...val.query.path.split('/').slice(1)]
}
}
},
methods: {
setQueryPath (index) { // 设置面包屑的query参数
const tmp = JSON.parse(JSON.stringify(this.breadcrumb))
if (index === 0) {
return '/'
} else {
return '/' + tmp.slice(1).slice(0, index).join('/')
// return tmp.slice(0, index + 1).join('/')
}
},
rowClick (row, column) { // 表格行被点击
this.$router.push({ path: '/info/resource', query: { path: row.path } })
},
}