I have this template within parent component:
<template>
<div>
<div
contenteditable
ref="editorContainer"
><editor-content :container-ref="$refs.editorContainer" /></div>
</div>
</template>
I have this props declaration within "editor-content" component:
props: {
//...
containerRef: {
type: Object,
}
},
but I get this warning:
[Vue warn]: Invalid prop: type check failed for prop "containerRef". Expected Object, got HTMLDivElement
What should be the type of the ref passing as a prop?
To allow only <div>
elements, use type HTMLDivElement
.
To allow any element, use type HTMLElement
.
To allow anything, set type to null
or undefined
(that way the linter won't issue a warning).
Here is a full example with TypeScript and Nuxt with SSR.
Added more context via comments.
<script lang="ts">
import { defineComponent, PropType, toRef, watchPostEffect } from '@nuxtjs/composition-api'
export default defineComponent({
props: {
element: {
// When using Nuxt SSR, use this otherwise you get error
// This allows any HTMLElement type, if want HTMLDivElement just change it
type: (process.server ? Object : HTMLElement) as PropType<HTMLElement>,
// let's make it explicit that it does not exist from the begining
default: undefined,
},
},
setup(props) {
// Because it can be undefined, let's use `toRef` instead of `toRefs`
const element = toRef(props, 'element')
// Optional Effect example
watchPostEffect((onInvalidate) => {
// This never happens, on post effect all refs are resolved
if (!element.value) return
// Your event listener
const onScroll = (e: Event) => console.log(e)
// Add event listener
element.value.addEventListener('scroll', onScroll, { passive: true })
// Remove event listener
onInvalidate(() => element.value.removeEventListener('scroll', onScroll))
})
},
})
</script>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.