前端表格的多对多组件

发布于 2022-08-14 19:51:25

后端配置

序列化器配置:

class UserSerializer(CustomModelSerializer):
    """
    用户管理-序列化器
    """
    role_info = DynamicSerializerMethodField()

    class Meta:
        model = Users
        read_only_fields = ["id"]
        exclude = ["password"]
        extra_kwargs = {
            "post": {"required": False},
        }

    def get_role_info(self, instance, parsed_query):
        roles = instance.role.all()
        serializer = RoleSerializer(
            roles,
            many=True,
            parsed_query=parsed_query
        )
        return serializer.data

接口返回的格式:

{
    ...
    role_info = [
        {"id":1,"name":"普通用户"},
        {"id":2,"name":"管理员"}
    ]
}

image.png

前端配置

crud配置:

component: {
name: 'manyToMany',
valueBinding: 'role_info',
children: 'name'
}

valueBinding:返回数据中的key;
children:valueBinding所绑定key中的显示字段;

完整配置(可查看用户管理):

{
        title: '角色',
        key: 'role',
        search: {
          disabled: true
        },
        minWidth: 130,
        type: 'table-selector',
        dict: {
          cache: false,
          url: '/api/system/role/',
          value: 'id', // 数据字典中value字段的属性名
          label: 'name', // 数据字典中label字段的属性名
          getData: (url, dict, {
            form,
            component
          }) => {
            return request({
              url: url,
              params: {
                page: 1,
                limit: 10
              }
            }).then(ret => {
              component._elProps.page = ret.data.page
              component._elProps.limit = ret.data.limit
              component._elProps.total = ret.data.total
              return ret.data.data
            })
          }
        },
        form: {
          rules: [ // 表单校验规则
            {
              required: true,
              message: '必填项'
            }
          ],
          itemProps: {
            class: { yxtInput: true }
          },
          component: {
            span: 12,
            pagination: true,
            props: { multiple: true },
            elProps: {
              columns: [
                {
                  field: 'name',
                  title: '角色名称'
                },
                {
                  field: 'key',
                  title: '权限标识'
                }
              ]
            }
          }
        },
        component: {
          name: 'manyToMany',
          valueBinding: 'role_info',
          children: 'name'
        }
      }
2 条评论

发布
问题