cascader中选中的值有两种展示方式,全部展开、收起。如下图

可惜这两种都不是我要的。我需要的是,第一个栏目中的元素不能选中,其中每个项目表示一个类目。选中值显示的规则是第一栏目中的项目只显示一次,如果同一个项目下的子节点选中了一个就直接展示该子节点的文字,否则显示该项目的名称+等x项。

具体代码如下
import { Cascader } from 'element-ui'
function getRootNode (node) {
return node.pathNodes[0]
}
const SubElCascader = {
mixins: [Cascader],
methods: {
// 覆写,参考了源码
computePresentTags () {
const checkedNodes = this.getCheckedNodes(false)
const tags = []
// 寻找所有选中节点的根节点
const rootNodes = []
checkedNodes.forEach(node => {
const rootNode = getRootNode(node)
if (rootNodes.indexOf(rootNode) === -1) {
rootNodes.push(rootNode)
}
})
rootNodes.forEach(rootNode => {
const nodesInTheSameRootNode = checkedNodes.filter(node => node.pathNodes[0] === rootNode)
let text
if (nodesInTheSameRootNode.length === 1) {
text = nodesInTheSameRootNode[0].data.label
} else {
text = rootNode.data.label + '等' + nodesInTheSameRootNode.length + '项'
}
tags.push({
key: rootNode.uid,
node: rootNode,
text,
hitState: false,
closable: true
})
})
this.checkedNodes = checkedNodes
this.presentTags = tags
},
deleteTag (index) {
const { checkedValue } = this
const rootNodeValue = this.presentTags[index].node.data.value
this.checkedValue = checkedValue.filter(val => val[0] !== rootNodeValue)
}
}
}
以上差不多是全部的代码了。我创建了一个vue项目,可以从这里下载,然后执行npm i, npm run dev就能看到效果了 https://download.youkuaiyun.com/download/Chinese521/12751448
发现在csdn上上传文件需要审核,都不知道什么时候能过审,我把代码放到了github上,有需要的小伙伴可以到github上看https://github.com/tangxuyang/demos/tree/master/cascader
如果有用,请点赞:)嘻嘻

本文介绍了一种在Element UI的Cascader组件中实现自定义选中值展示的方法,使得第一个栏目中的元素不可选,并按特定规则显示选中值,通过覆写组件方法实现功能。
1万+

被折叠的 条评论
为什么被折叠?



