6.1 KiB
- Organize Your Code into Logical Sections
Structure your component script into clear sections to improve readability. A common approach is to group related logic together. Example Structure:
- Use script setup Syntax
The
{{ message }}
- Use Descriptive Variable and Function Names
Choose meaningful names for variables, functions, and computed properties to make your code self-documenting. Example: // Bad const x = ref(0)
// Good const userCount = ref(0)
- Extract Reusable Logic into Composables Move reusable logic into composables (custom hooks) to keep your components clean and promote code reuse. Example Composable:
// composables/useCounter.js import { ref } from 'vue'
export function useCounter(initialValue = 0) { const count = ref(initialValue)
function increment() { count.value++ }
function reset() { count.value = initialValue }
return { count, increment, reset, } }
Usage in a Component:
Count: {{ count }}
Increment-
Use ref for Primitive Values and reactive for Objects
- Use ref for primitive values (e.g., numbers, strings, booleans).
- Use reactive for objects or arrays.
Example: const count = ref(0) // Primitive value const user = reactive({ name: 'John', age: 30 }) // Object
- Use Computed Properties for Derived State
Use computed to create reactive properties that depend on other state. This ensures the derived state is always up-to-date. Example: const firstName = ref('John') const lastName = ref('Doe')
const fullName = computed(() => ${firstName.value} ${lastName.value}
)
- Use Watchers Sparingly
Watchers (watch and watchEffect) are powerful but can make your code harder to understand if overused. Prefer computed properties or event-driven updates where possible.
Example:
watch(count, (newValue, oldValue) => {
console.log(Count changed from ${oldValue} to ${newValue}
)
})
- Group Related Logic Together
Keep related reactive state, computed properties, and functions together to make your code easier to follow. Example: // User-related logic const user = reactive({ name: 'John', age: 30 }) const isAdult = computed(() => user.age >= 18) function updateUser(newName) { user.name = newName }
- Use Lifecycle Hooks for Side Effects
Use lifecycle hooks (onMounted, onUnmounted, etc.) for side effects like fetching data or setting up event listeners. Example: onMounted(() => { console.log('Component mounted') fetchData() })
onUnmounted(() => { console.log('Component unmounted') cleanup() })
- Use TypeScript for Better Type Safety If your project uses TypeScript, leverage it to add type safety to your components. Example:
- Keep Templates Clean
Avoid putting too much logic in your template. Instead, move complex logic into the script or composables. Example:
{{ fullName }}
Increment- Use provide and inject for Prop Drilling Avoid prop drilling by using provide and inject to share state across deeply nested components. Example: // Parent component import { provide, ref } from 'vue'
const theme = ref('dark') provide('theme', theme)
// Child component import { inject } from 'vue'
const theme = inject('theme')
- Use v-model for Two-Way Binding
Use v-model to simplify two-way binding between parent and child components. Example:
- Use defineProps and defineEmits for TypeScript Support
When using TypeScript, use defineProps and defineEmits to define props and emits with type safety. Example:
- Use Scoped Styles
Use scoped styles (
- Use Environment Variables
Use environment variables for configuration (e.g., API URLs) to keep your code flexible and secure. Example: const apiUrl = import.meta.env.VITE_API_URL
- Write Unit Tests
Write unit tests for your components and composables to ensure they work as expected. Example: import { render } from '@testing-library/vue' import MyComponent from '@/components/MyComponent.vue'
test('renders correctly', () => { const { getByText } = render(MyComponent) expect(getByText('Hello, Vue 3!')).toBeInTheDocument() })