Skip to content

自定义组件无法使用useAttrs()获取props值 #769

@Thorns-Set

Description

@Thorns-Set

"@form-create/iview4": "^2.5.28",

<template>
  <BizOrgUserModal
    v-bind="filteredProps"
    v-model="innerValue"
    :disabled="effectiveDisabled"
    :name="innerName"
    @inputClick="inputClick"
    @update:name="(val) => emit('update:name', val)"
  />
</template>

<script setup>
import { computed, onMounted, ref, useAttrs } from 'vue'
import { useDictItem } from '@/hooks'
import { isBooleanTrue } from '@/utils'

const props = defineProps({
  disabled: { type: Boolean, default: false },
  value: { type: [String, Number, Array], default: () => [] },
  name: { type: [String, Number], default: '' },
  enabledIcMonitor: { type: Boolean, default: false }
})
const emit = defineEmits(['input', 'update:name', 'inputClick'])

// 控制是否禁用
const effectiveDisabled = ref(props.disabled)
const forceSwipingCard = ref(false)

onMounted(async () => {
  try {
    const { value: dictValue } = await useDictItem({
      type: 'tenant.config',
      field: 'key',
      value: 'forceSwipingCard'
    })
    forceSwipingCard.value = isBooleanTrue(dictValue)
    if (forceSwipingCard.value) {
      effectiveDisabled.value = true
    }
  } catch (e) {
    // 保留默认 disabled
  }
})

// 包装 v-model:读取 props.value,修改时触发 input 事件
const innerValue = computed({
  get: () => props.value,
  set: (val) => emit('input', val)
})

// 包装 name.sync:读取 props.name,修改时触发 update:name
const innerName = computed({
  get: () => props.name,
  set: (val) => emit('update:name', val)
})

// 透传除 disabled、value、name 外的其他属性
const filteredProps = computed(() => {
  console.log(JSON.stringify(useAttrs()))
  const { disabled, value, name, ...rest } = useAttrs()
  return rest
})

// 点击输入框时,透传 forceSwipingCard 标志
const inputClick = () => emit('inputClick', forceSwipingCard.value)
</script>

<style scoped></style>

defineProps中定义后可以正常获取useAttrs()值为空

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions