下午遇到一个需求: 要求树只能单选 (我们用的 Element-ui 的 tree 组件, 官方文档默认支持的是多选), 现将实现单选的方法记录下:
template 中新增如下:
- <el-tree
- @check-change="handleCheckChange"
- :props="defaultProps">
- </el-tree>
script 中新增如下
- methods: {
- handleCheckChange (data, checked, indeterminate) {
- let {id} = data
- let index = this.checked.indexOf(id)
- // 当前节点不在 this.checked 中, 且当前节点为选中状态
- if (index <0 && this.checked.length && checked) {
- this.$message.warning('只能选中一个节点')
- this.$refs.tree.setChecked(data, false) // 取消当前节点的选中状态
- return
- }
- // 当前节点在 this.checked 中, 当前节点为未选中状态 (主动去掉当前选中状态)
- if (!checked && index>= 0 && this.checked.length) {
- this.checked = []
- return
- }
- // 当前节点不在 this.checked(长度为 0) 中, 当前节点为选中状态, this.checked 中存储当前节点 id
- if (index < 0 && !this.checked.length && checked) {
- this.checked.push(id)
- }
- },
- },
- data () {
- return {
- checked: [], // 存储选中节点的 id
- }
- }
在线 demo 地址为: https://codepen.io/pen/?&editable=true
来源: http://www.bubuko.com/infodetail-3451332.html