I'm starting with VUE 3 and the composition api using Typescript for the first time.
I have the setup method like the following:
setup(props: { widgetType: string; displayType: string; trigger: number }, { emit })
Now, when I'm building this file, I get the error "Binding element 'emit' implicitly has an 'any' type.".
I do not know how to fix this. I tried different solutions from the web but nothing worked.
Can anybody help me?
Regards
Chris
-
How have you defined your component?Dan– Dan2021-03-01 15:32:09 +00:00Commented Mar 1, 2021 at 15:32
Add a comment
|
2 Answers
You need to define your component with the defineComponent method and apply the correct type to props. If you are using single file components it would look something like this
<script lang="ts">
import { defineComponent } from 'vue'
export default defineComponent({
props: {
widgetType: {
type: String,
required: true
},
displayType: {
type: String,
required: true
},
trigger: {
type: number,
required: true
}
},
setup(props, { emit }) {
// Rest of your setup code here
}
});
</script>
Comments
For example correct typing with component "App" and composable "useModal"
App:
<script lang="ts">
import {defineComponent, SetupContext, ComponentPropsOptions} from 'vue';
import {useModal} from '@/composable/useModal';
export default defineComponent({
name: 'App',
emits: ['openModal'],
setup(props: ComponentPropsOptions, {emit}: SetupContext) {
const openModal = useModal({emit});
return {openModal};
}
});
</script>
useModal:
import {SetupContext} from 'vue';
interface UseModalProps {
emit: SetupContext['emit'];
}
export function useModal({emit}: UseModalProps) {
function openModal({title, type}: {title: string; type: string}): void {
emit('openModal', {title, type});
}
return {openModal};
}
2 Comments
commonpike
Shouldn't you still define
emits: ['openModal'] in the App ?Denis Grushak
You are right, I have edited the example.