Vue.js + Typescript best practices

I will evolve this template here as a personal reference.

Vue.js + Typescript best practices

<template>
  <!--
    Brief description of the component.
    @component [ComponentName]
  -->
  <div>
    <!-- Your template code here -->
  </div>
</template>

<script setup lang="ts">
/**
 * Imports
 * Import necessary modules, components, or utilities here.
 */
import { ref, computed } from 'vue';

/**
 * Props
 * Define the props with their types and default values (if any).
 * Always document what each prop is for.
 */
interface Props {
  /**
   * @prop {Type} propName - Brief description of the prop.
   */
  propName: string;
}

const props = defineProps<Props>();

/**
 * Emits
 * Define the emits with their types. Document what each event is for.
 */
const emit = defineEmits<{
  (event: 'update:modelValue', value: string): void;
}>();

/**
 * Refs
 * Initialize your refs here. Refs are used to create reactive data.
 * Document each ref explaining its purpose.
 */
const myRef = ref<string>('');

/**
 * Computed Properties
 * Use computed properties to derive data.
 * Document each computed property explaining what it is derived from.
 */
const computedValue = computed(() => {
  // Compute something based on props or refs
  return props.propName.toUpperCase();
});

/**
 * Lifecycle Hooks
 * Optionally use Vue lifecycle hooks.
 * Document why each lifecycle hook is used.
 */
onMounted(() => {
  // Code to run on mount
});

/**
 * Methods/Functions
 * Define any functions or methods needed for this component.
 * Document each function explaining its purpose and parameters.
 */
function handleClick(): void {
  // Handle a click event
  emit('update:modelValue', myRef.value);
}

</script>

<style scoped>
/* 
  Add scoped styles here 
  Document what each CSS class is for.
*/
</style>

Leave a Reply