在 Vue.js 中使用 Element UI 的 el-tree 组件选择组织机构时,有时会遇到 formData.deptIds 为 undefined 的问题。这是因为在修改组织机构的勾选值时,未正确更新 formData.deptIds 的值。

为了解决这个问题,需要在修改组织机构的勾选值后,将其正确地赋值给 formData.deptIds。

1. 在 el-tree 组件中添加 node-checked-change 事件监听器:

<el-tree :data="deptTreeData" show-checkbox default-expand-all :default-checked-keys="deptList"
    node-key="deptId" highlight-current :props="defaultDeptProps" :check-strictly="true"
    @node-checked-change="handleDeptCheckedChange" />

2. 定义 handleDeptCheckedChange 函数,用于更新 formData.deptIds:

function handleDeptCheckedChange(checkedNodes) {
    formData.deptIds = checkedNodes.map(node => node.deptId);
}

**3. 确保 formData 是一个响应式对象。**可以使用 reactive 函数进行声明:

const formData = reactive({
    deptIds: []
});

通过以上步骤,就可以解决 formData.deptIds 为 undefined 的问题。

其他建议:

  • 使用 console.log() 打印 checkedNodes 和 formData.deptIds 的值,以便更好地理解数据流。
  • 仔细检查代码,确保在更新 formData.deptIds 之前,checkedNodes 已经正确获取。

示例代码:

<template>
  <el-form-item label="组织机构" prop="deptIds">
    <div class="flex justify-between">
      <el-row>
        <el-tree :data="deptTreeData" show-checkbox default-expand-all :default-checked-keys="deptList"
            node-key="deptId" highlight-current :props="defaultDeptProps" :check-strictly="true"
            @node-checked-change="handleDeptCheckedChange" />
      </el-row>
    </div>
  </el-form-item>
</template>

<script setup>
import { reactive } from 'vue';

const defaultDeptProps = {
    children: 'children',
    label: 'deptName',
};

const deptTreeData = reactive<any>([]);

const formData = reactive({
    deptIds: []
});

function handleDeptCheckedChange(checkedNodes) {
    formData.deptIds = checkedNodes.map(node => node.deptId);
    console.log('33333333按下了submit', formData.deptIds);
}

// ... 其他代码 ...
</script>

通过以上方法,就可以在表单中正确地更新组织机构的勾选值,并解决 formData.deptIds 为 undefined 的问题。

Vue.js 中 El-Tree 组件组织机构勾选值更新问题

原文地址: https://www.cveoy.top/t/topic/plbb 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录