I am trying to learn Vue 3 Composition API with TypeScript, specifically how to emit events with a strictly typed payload.
I have an example below but i'm not sure if it is the correct way. So my question is if there are any other methods to emit events with a strictly typed payload?
Example
I used this package: https://www.npmjs.com/package/vue-typed-emit and got it to work with the example below where I am passing a boolean from a child component to the parent:
Child component:
<script lang="ts">
import { defineComponent, ref, watch } from 'vue'
import { CompositionAPIEmit } from 'vue-typed-emit'
interface ShowNavValue {
showNavValue: boolean
}
interface ShowNavValueEmit {
emit: CompositionAPIEmit<ShowNavValue>
}
export default defineComponent({
name: 'Child',
emits: ['showNavValue'],
setup(_: boolean, { emit }: ShowNavValueEmit) {
let showNav = ref<boolean>(false)
watch(showNav, (val: boolean) => {
emit('showNavValue', val)
})
return {
showNav
}
}
})
</script>
Parent component
<template>
<div id="app">
<Child @showNavValue="toggleBlurApp" />
<div :class="{'blur-content': blurApp}"></div>
</div>
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue';
import Child from './components/Child.vue';
export default defineComponent({
name: 'Parent',
components: {
Child
},
setup() {
let blurApp = ref<boolean>(false);
let toggleBlurApp = (val: boolean) => {
blurApp.value = val;
}
return {
blurApp,
toggleBlurApp
}
}
});
</script>
<style lang="scss">
.blur-content{
filter: blur(5px);
transition : filter .2s linear;
}
</style>