Element-ui Tree组件实现单选

  下午遇到一个需求:要求树只能单选(我们用的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

猜你喜欢

转载自www.cnblogs.com/hanshuai/p/12435613.html