element-ui el-cascader級聯選擇器設置指定層級不能選中


有時候用element-ui el-cascader級聯選擇器添加分類時會遇到最多添加幾級的限定.看了文檔,只要給需要禁止選擇的選項添加disabled屬性就可以.但是使用一層一層循環遍歷數據感覺很麻煩,自己寫了個遍歷的方法,紀錄下,方便以后使用

貼代碼
cascader.vue<template>
  <el-dialog title="添加分類" :visible.sync="dialogVisible" width="500px">
    <div class="role_contanier">
      <el-form label-width="80px" :model="typeInfo">
        <el-form-item label="分類名稱">
          <el-input v-model="typeInfo.name"></el-input>
        </el-form-item>
        <el-form-item label="分類組">
          <el-cascader v-model="typeInfo.group" :options="typeOptions" :props="props" @change="handleChange">
          </el-cascader>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">添加</el-button>
        </el-form-item>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="dialogVisible = false">確 定</el-button>
    </span>
  </el-dialog>
</template>
  
  <script> export default { props: { }, data() { return { dialogVisible: false, typeInfo: { group: '', name: '' }, typeOptions: [], // 分類層級選項
 props: { label: 'name', // 顯示的選項
          value: 'id', // 選擇的value值
          children: 'childs', // 子級屬性名
          checkStrictly: true // 可以選擇任意一級
        } // 指定層級屬性
 } }, created() { this.getTypeOptions() }, mounted() { }, methods: { // 獲取分類級別
 getTypeOptions () { // 假設后台返回的數據 4級
        let resDate = [{ id: 1, name: '食品', childs: [ {id: 3, name: '進口食品', childs: [ {id: 5, name: '果干', childs: [{id: 7, name: '堅果',}]}, {id: 6, name: '面包'} ] }, {id: 4, name: '國內食品'} ] }, {id: 2, name: '清潔'} ] // 限制只能添加4級分類
        this.setDisable (1, resDate, 3) console.log(resDate) this.typeOptions = resDate this.dialogVisible = true }, // 超過3級,不能選中,子級分類最多4級
      /** * count: 當前層級 * data: 當前層級的數據 * maxNum: 最多不能超過幾級 */ setDisable (count, data, maxNum) { if (count > maxNum) { //最多幾級就寫幾
          data.forEach(v => { v.disabled = true // 超過設定的最大級數,給這一集的數據添加disabled屬性
 }) } else { data.forEach(v => {
       v.count = count // 設置最外層數據的初始count
if (v.childs && v.childs.length) { v.count++ this.setDisable(v.count, v.childs, maxNum) // 子級循環時把這一層數據的count傳入 } }) } }, // 添加分類 submitForm () { }, handleChange (val) { console.log(val) } } } </script> <style> </style>

 效果圖: 第4級,(堅果不能被選中,也就不能再往下添加分類)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM