--- description: Comprehensive guidelines for Vue.js development, covering code structure, performance, security, testing, and tooling best practices. This rule provides actionable guidance to enhance code quality, maintainability, and developer productivity in Vue.js projects. globs: *.vue, *.js, *.ts --- # Vue.js Best Practices and Coding Standards This document outlines best practices for Vue.js development, covering various aspects to ensure high-quality, maintainable, and performant code. ## 1. Code Organization and Structure ### 1.1. Directory Structure * **Component-Based Structure:** Organize components into logical folders based on their functionality or feature. This improves code readability and maintainability. src/ ├── components/ │ ├── Button/ │ │ ├── Button.vue │ │ └── Button.spec.js │ ├── Input/ │ │ ├── Input.vue │ │ └── Input.spec.js │ └── ... ├── views/ │ ├── Home.vue │ ├── About.vue │ └── ... ├── services/ │ ├── api.js │ └── auth.js ├── store/ │ ├── index.js # Vuex store │ ├── modules/ │ │ ├── user.js │ │ └── ... ├── App.vue └── main.js * **Feature-Based Structure:** Alternatively, organize files by feature, grouping components, routes, and store modules related to a specific feature. src/ ├── features/ │ ├── user-profile/ │ │ ├── components/ │ │ │ ├── UserProfile.vue │ │ │ └── ... │ │ ├── routes.js │ │ ├── store.js │ │ └── ... │ ├── shopping-cart/ │ │ ├── ... │ └── ... ├── App.vue └── main.js ### 1.2. File Naming Conventions * **Component Files:** Use PascalCase for component file names (e.g., `MyComponent.vue`). * **Other Files:** Use camelCase or kebab-case for other JavaScript/TypeScript files (e.g., `apiService.js`, `my-helper.js`). * **Consistency:** Maintain a consistent naming convention throughout the project. ### 1.3. Module Organization * **ES Modules:** Utilize ES modules (`import`/`export`) for modular code organization. * **Single Responsibility Principle:** Each module should have a single, well-defined responsibility. * **Avoid Circular Dependencies:** Prevent circular dependencies between modules to avoid unexpected behavior and improve maintainability. ### 1.4. Component Architecture * **Component Composition:** Favor component composition over inheritance for increased flexibility and reusability. * **Presentational and Container Components:** Separate presentational (dumb) components from container (smart) components. Presentational components focus on rendering UI, while container components handle data fetching and logic. * **Single File Components (SFCs):** Leverage Vue's SFCs for encapsulating component logic, template, and styling. ### 1.5. Code Splitting Strategies * **Route-Based Splitting:** Use dynamic imports and Vue's `async` component feature to split the application into chunks based on routes. * **Component-Based Splitting:** Split large components into smaller, lazy-loaded components to improve initial load time. * **Vendor Splitting:** Separate vendor dependencies into a separate chunk to allow for browser caching and prevent unnecessary reloads. ## 2. Common Patterns and Anti-patterns ### 2.1. Design Patterns Specific to Vue * **Provide/Inject:** Use `provide` and `inject` for dependency injection between components, especially when dealing with deeply nested components. * **Renderless Components:** Create renderless components that encapsulate logic and provide data to be rendered by slot-using components. * **Higher-Order Components (HOCs):** Use HOCs to reuse component logic or add functionality to existing components. ### 2.2. Recommended Approaches for Common Tasks * **Form Handling:** Use `v-model` for two-way data binding in forms. Consider using a form validation library like Vuelidate or VeeValidate for robust form validation. * **API Requests:** Use a dedicated service module for handling API requests. Use `async/await` for cleaner asynchronous code. * **State Management:** Utilize Vuex for centralized state management in larger applications. For simpler applications, consider using Vue's reactivity system directly or a lightweight state management solution like Pinia. * **Event Handling:** Use component events (`$emit`) for communication between parent and child components. For communication between unrelated components, use a global event bus (with caution) or a state management solution. ### 2.3. Anti-patterns and Code Smells to Avoid * **Mutating Props Directly:** Avoid mutating props directly within a component. Instead, emit an event to the parent component to update the prop value. * **Overusing Global State:** Avoid storing too much data in global state. Use local component state whenever possible. * **Direct DOM Manipulation:** Avoid directly manipulating the DOM using `document` APIs. Use Vue's template directives and component APIs to update the DOM reactively. * **Magic Numbers and Strings:** Avoid using magic numbers and strings directly in the code. Use constants to improve readability and maintainability. * **Complex Computed Properties:** Keep computed properties simple and focused. Complex computations should be moved to methods or utility functions. ### 2.4. State Management Best Practices * **Single Source of Truth:** Maintain a single source of truth for application state using Vuex or Pinia. * **Mutations for State Updates:** Only use mutations to update the state in Vuex. Mutations should be synchronous and atomic. * **Actions for Asynchronous Operations:** Use actions to handle asynchronous operations like API requests. Actions can commit mutations to update the state. * **Getters for Derived State:** Use getters to derive state from the store. Getters should be pure functions and should not modify the state. * **Modularity:** Organize the store into modules to improve maintainability and scalability. ### 2.5. Error Handling Patterns * **Centralized Error Handling:** Implement a centralized error handling mechanism to catch and log errors consistently. * **Error Boundary Components:** Use error boundary components to catch errors within specific parts of the application and prevent crashes. * **User-Friendly Error Messages:** Provide user-friendly error messages to guide users when errors occur. * **Logging:** Log errors to a server or error tracking service for monitoring and debugging. * **Try-Catch Blocks:** Use `try-catch` blocks to handle potential errors in asynchronous operations or complex computations. ## 3. Performance Considerations ### 3.1. Optimization Techniques * **Virtual DOM Optimization:** Vue's virtual DOM implementation is already highly optimized, but avoid unnecessary re-renders by using `v-if` instead of `v-show` when elements are rarely displayed. * **Computed Properties and Watchers:** Use computed properties and watchers judiciously. Avoid performing expensive computations in computed properties that are frequently re-evaluated. Debounce or throttle watchers to limit the number of updates. * **List Rendering Optimization:** Use the `:key` attribute when rendering lists with `v-for` to help Vue track changes efficiently. Ensure the keys are unique and stable. * **Functional Components:** Use functional components for simple, stateless components to improve rendering performance. * **Avoid Inline Templates:** Use pre-compiled templates in single-file components instead of inline templates (using `