Subscribe on changes!

How to write a custom component which inherit props from an existing one?

avatar
Jan 28th 2021

What problem does this feature solve?

for example, in react, I can define a custom input component like this:

function MyInput(props: React.PropsWithChildren<React.HTMLProps<HTMLInputElement>> & {
  foo: string
}) {
  const [value, setValue] = useState('')
  const onChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    console.log(props.foo)
    setValue(e.target.value)
  }, [])
  return <input {...props} value={value} onChange={onChange} />
}

What does the proposed API look like?

Vue.HTMLProps

avatar
Jan 28th 2021
avatar
Jan 28th 2021

You can use $attrs to passthrough, for example, https://codepen.io/hcysunyang/pen/abBoRpQ, also check out https://v3.vuejs.org/guide/component-attrs.html#attribute-inheritance

checked the example but it's not written by typescript and MyInput is a plan object without props type definition...

avatar
Jan 28th 2021

by the way, I can use Omit<React.HTMLProps, 'value', 'placeholder'> to filter out props

You can use $attrs to passthrough, for example, https://codepen.io/hcysunyang/pen/abBoRpQ, also check out https://v3.vuejs.org/guide/component-attrs.html#attribute-inheritance

checked the example but it's not written by typescript and MyInput is a plan object without props type definition...

avatar
Jan 28th 2021

So, what are you really asking? is it about the pass-through props? or about TS type?

avatar
Jan 28th 2021

So, what are you really asking? is it about the pass-through props? or about TS type?

with ts I can get both type definition(for auto completion) and props inherition

avatar
Jan 28th 2021

you can also do this:

import { FunctionalComponent } from 'vue'

const MyInput: FunctionalComponent<InputHTMLAttributes & { foo?: string}> = (props) => {
  return <input {...props}/>
}

const el = <MyInput foo="str" autofocus  />
avatar
Jan 28th 2021

you can also do this:

import { FunctionalComponent } from 'vue'

const MyInput: FunctionalComponent<InputHTMLAttributes & { foo?: string}> = (props) => {
  return <input {...props}/>
}

const el = <MyInput foo="str" autofocus  />

FunctionalComponent is exactly what I need! but I receive compile error TS2304: Cannot find name 'InputHTMLAttributes'. should I import @types/react into a vue project?

avatar
Jan 28th 2021

import it from vue:

import { InputHTMLAttributes } from 'vue
avatar
Jan 28th 2021

import it from vue:

import { InputHTMLAttributes } from 'vue

it works! thank you

avatar
Feb 16th 2022

you can also do this:

import { FunctionalComponent } from 'vue'

const MyInput: FunctionalComponent<InputHTMLAttributes & { foo?: string}> = (props) => {
  return <input {...props}/>
}

const el = <MyInput foo="str" autofocus  />

使用 单文件组件的时候怎么做呢? 用defineComponent包裹