如何在 Vue 中扩展原生 HTML 元素的 prop 类型?

问题描述 投票:0回答:2

假设我有一个元素,它包装了一个输入并获取其所有属性,此外还有一些属性。

在反应中,这将被输入为

interface ExtendedInputProps extends React.ComponentPropsWithoutRef<'input'> {
    some: Type
}

这是一个非常常见的用例。我知道 Vue 3 根据传递给 DefineComponent 中

props:
对象的内容生成其 prop 类型。

我正在想象做类似的事情:

props:{
    ...getComponentProps('input')
    additionalProp: String
}

但我不知道该怎么做,也找不到任何相关文档。可以吗?

typescript vue.js vuejs3
2个回答
2
投票

最简单的情况是当 input 是组件的根元素时,那么你不需要声明任何额外的东西,只需将属性传递给你的组件,它们就会向下传递

//NumberInput Component
<template>
    <input :value="modelValue"
      @input="$emit('update:modelValue', $event.target.value)"  />
</template>

<script setup lang="ts">
defineEmits(["update:modelValue"])
const props = withDefaults(defineProps<{
    modelValue?: number
}>(), { modelValue: 0 })
</script>

可以这样使用:

<number-input v-model="data" type="text" placeholder="123-45-678" />

其中

type
placeholder
最终将作为输入元素的属性。

如果您的组件内嵌套有输入,则需要禁用属性继承:

//NumberInput Component
<template>
  <div class="wrapper">
    <input :value="modelValue" v-bind="$attrs" 
      @input="$emit('update:modelValue', $event.target.value)"  />
  </div>

</template>

<script setup lang="ts">
defineEmits(["update:modelValue"])
const props = withDefaults(defineProps<{
    modelValue?: number
}>(), { modelValue: 0 })
</script>

<script lang="ts">
// normal `<script>`, executed in module scope (only once)
// declare additional options
export default {
  inheritAttrs: false,
  customOptions: {}
}
</script>

请注意,我们添加了第二个脚本标签来禁用

inheritAttrs
,并将
v-bind="$attrs"
添加到输入以显式向下传递属性。有关该主题的更多信息,您可以在此处

找到

0
投票

最接近的写法可能是:

<script lang="ts" setup>
import type { InputHTMLAttributes } from 'vue'

interface MyInputProps extends /* @vue-ignore */ InputHTMLAttributes {
  some?: Type
}

defineProps<MyInputProps>()
</script>

它适用于我的

[email protected]

© www.soinside.com 2019 - 2024. All rights reserved.