Skip to content
On this page

Components

Structure

When writing components, you should always follow this structure.

ElementExample
1. Importsimport { defineProps, defineEmits } from 'vue';
2. Propsconst props = defineProps<{value: Person}>();
3. Emitsconst emit = defineEmits<{(e: 'change', value: Person)}>();
4. Composableconst { isLoading } = useLoading()
5. Refsconst isLoading = ref<boolean>(false)
6. Computed propertiesconst isLoading = computed<boolean>(() => {})
7. MethodsinitForm() {}
8. Lifecycle hooksonMounted(() => {})
9. defineExposedefineExpose({})
10. Template<template>
11. Styles<style scoped>

Example of a well-structured component:

vue
<script lang="ts">
import { defineProps, defineEmits } from 'vue';

const props = defineProps<{
  value: Person,
}>();

const emit = defineEmits<{
  (e: 'change', value: Person),
}>();

const employeeStore = useEmployeeStore();

const employeeForm = ref<EmployeeForm>({
  firstName: ''
});

const isLoading = computed<boolean>(() => {
  return employeeStore.isLoading;
});

const initForm = () => {
  employeeForm.value = {
    firstName: ''
  };
};

onMounted(() => {
  initForm();
});

defineExpose({
  initForm,
});
</script>

<template>
  <section>
    <form class="space-y-2">
      <FormInput 
          v-model="employeeForm.firstName"
          label="First name"
      />
      <button @click="initForm">Add Employee</button>
    </form>
  </section>
</template>

<style scoped>
button {
  background-color: black;
}
</style>