Vue 3 Script Settings Typescript | Implicitly entered "el" parameter in template reference
P粉883278265
P粉883278265 2024-02-21 11:48:20
0
1
318

Can anyone tell me why typescript is yelling at me with the following error? error TS7006: Parameter 'el' implicitly has type 'any'. ref="(el) => saveRef(index, el)". I'm pretty sure the correct type is set in the saveRef function.

<script lang="ts" setup>
    import FormComponent from '@/components/FormComponent.vue'

    const formRefs = ref<
      ComponentPublicInstance<typeof FormComponent>[]
    >([])

    function saveRef(
      index: number,
      el: ComponentPublicInstance<typeof FormComponent>
    ) {
      formRefs.value[index] = el
    }

    onBeforeUpdate(() => {
      formRefs.value = []
    })
  </script>

  <template>
    <div v-for="(component, index) in components" :key="index">
      <form-component
        :ref="(el) => saveRef(index, el)"
        :component="component"
        :index="index"
      />
   </div>
 </template>

P粉883278265
P粉883278265

reply all(1)
P粉020556231

It is generally not a good practice to keep redundant JS in templates. The correct solution is to define typed reference handling functions in the component script. Since it should be parameterized, it can be a higher-order function:

function saveRef(
  index: number,
) {
  return (el: ComponentPublicInstance) => {
    formRefs.value[index] = el
  }
}

and use it as :ref="saveRef(index)".

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template