[Vue] Typescript for Vue3 (defineProps, withDefaults, defineEmits)

Zhentiw發表於2024-11-27

Define a component with props and defualt props value

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import fetchCount from '../services/fetchCount'

interface Props {
  limit: number,
  alertMessageOnLimit?: string
}

const props = withDefaults(defineProps<Props>(), {
  alertMessageOnLimit: 'can not go any higher' // default value
})

const count = ref<number | null>(null)

onMounted(() => {
  fetchCount((initialCount) => {
    count.value = initialCount
  })
})

function addCount(num: number) {
  if (count.value !== null) {
    if (count.value >= props.limit) {
      alert(props.alertMessageOnLimit)
    }
    else {
      count.value += num
    }
  }
}

</script>

<template>
  <p>{{ count }}</p>
  <p>
    <button @click="addCount(1)">Add</button>
  </p>
</template>

Component with emits

<script setup lang="ts">

const emit = defineEmits<{ 
  (event: 'add-count', num: number): void  
  (event: 'reset-count'): void 
}>()

</script>

<template>
  <p>
    <button @click="emit('add-count', 1)">Add</button>
    <button @click="emit('reset-count')">Reset</button>
  </p>
</template>

相關文章