-
Notifications
You must be signed in to change notification settings - Fork 1
07_Vue Code Guidelines
This page gives basic guidance on developing Vue components. It's highly recommended to read the Vue 3 Documentation beforehand.
Components should be named in PascalCase
, e.g. SomeComponent.vue
.
Additionally, component names should (usually) end in the corresponding component folder's name:
components
├── forms
│ ├── LoginForm.vue
│ └── SignupForm.vue
│
├── dialogs
│ └── ErrorDialog.vue
│
├── tables
│ ├── EmployeeTable.vue
│ └── SalaryTable.vue
Similarly, Page Components' names should also end in Page
, e.g. MyDashboardPage.vue
.
We use script setup in all Vue components. Additionally, lang='ts'
has to be specified in order for the script block to use TypeScript:
<script setup lang='ts'>
...
</script>
All variables defined within the <script setup>
are directly available to the template. If a variable should be reactive, it must be a ref.
The below example shows a minimal component where one value (username
) within the template can be updated.
<template>
<div>
<h2>
{{ welcome }}
</h2>
<p>
Hello, {{ username }}
</p>
</div>
</template>
<script setup lang='ts'>
const welcome = 'Welcome'
const username = ref('someone')
/**
* Updates the username
* @param {string} name - the new name
* @returns {void}
*/
function updateName(name: string){
username.value = name
}
</script>
Some key points for writing templates:
- Write data bindings according to Vue's own standards, with a space before and after variable names:
<template>
<!-- OK -->
{{ example }}
<!-- Wrong -->
{{example}}
</template>
- Avoid writing complex logic in templates; in many cases, a computed property is more suitable:
<template>
<!-- OK -->
<SomeComponent
:values="filteredValues"
/>
<!-- Wrong -->
<SomeComponent
:values="values.filter((value) => value > filterLevel && someCondition)"
/>
</template>
<script setup lang='ts'>
import {computed} from 'vue';
const filteredValues = computed(() => {
return values.filter((value) => value > filterLevel && someCondition)
})
</script>
Use kebab-case
for Events, because they are listened to in that way in the template.
ChildComponent.vue
:
<script setup lang='ts'>
import {defineEmits} from 'vue';
const emit = defineEmits('some-event')
</script>
ParentComponent.vue
:
<template>
<ChildComponent
@some-event='doSomething'
/>
</template>