vue中实现选父带子,选子不带父,取子不取父

<el-cascader
            ref="cascader"
            v-model="userFrom.major"
            :show-all-levels="false"
            :props="{ value: 'id',label: 'name',children: 'childList', multiple: true,checkStrictly: true}"
            :options="subject"
          />
watch
  watch: {
    'userFrom.major': {
      handler(newArr, oldArr) {
        const current = this.findCurrentDepartment(newArr, oldArr)
        if (!current) return
        this.$nextTick(() => {
          if (current.type === 'checked') {
            // 从级联选择器中取出内部的节点数组,找到当前节点
            const targetNode = this.$refs.cascader.checkedNodes.find((item) => {
              return item.value === current.value[current.value.length - 1]
            })
            if (targetNode) {
              // 递归找出所有子孙节点,并手动勾选
              this.checkedChildrenDepartment([targetNode])
              // 更新视图
              this.$refs.cascader.$refs.panel.calculateMultiCheckedValue()
            }
          }
        })
      },
      deep: true
    }
  },
methods
  methods: {
    checkedChildrenDepartment(list = []) {
      list.forEach((item) => {
        item.doCheck(true)
        if (item.children.length > 0) {
          this.checkedChildrenDepartment(item.children)
        }
      })
    },
    findCurrentDepartment(newArr, oldArr) {
      const catchNewArr = [...newArr]
      const catchOldArr = [...oldArr]
      if (catchNewArr.length > catchOldArr.length) {
        console.log('为添加')
        for (let i = 0; i < catchNewArr.length; i++) {
          const targetIndex = catchOldArr.indexOf(catchNewArr[i])
          if (targetIndex === -1) {
            return {
              value: catchNewArr[i],
              type: 'checked'
            }
          }
        }
      } else {
        console.log('为取消')
        for (let i = 0; i < catchOldArr.length; i++) {
          const targetIndex = catchNewArr.indexOf(catchOldArr[i])
          if (targetIndex === -1) {
            return {
              value: catchOldArr[i],
              type: 'cancel'
            }
          }
        }
      }
    },
}

  

posted @ 2024-09-10 17:44  东峰叵,com  阅读(7)  评论(0编辑  收藏  举报