Home > Web Front-end > JS Tutorial > General Coding Standards for Vue js.

General Coding Standards for Vue js.

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2024-08-06 19:15:22
Original
1107 people have browsed it

General Coding Standards for Vue js.

Here are additional good and bad practices for Vue.js:

General Coding Standards

  1. Avoid Magic Numbers and Strings:
    • Use constants for values that are used repeatedly or have special meaning.
   // Good
   const MAX_ITEMS = 10;

   function addItem(item) {
     if (items.length < MAX_ITEMS) {
       items.push(item);
     }
   }

   // Bad
   function addItem(item) {
     if (items.length < 10) {
       items.push(item);
     }
   }
Copy after login
  1. Use v-for Efficiently:
    • When using v-for, always provide a unique key to optimize rendering.
   <!-- Good -->
   <div v-for="item in items" :key="item.id">
     {{ item.name }}
   </div>

   <!-- Bad -->
   <div v-for="item in items">
     {{ item.name }}
   </div>
Copy after login
  1. Avoid Inline Styles:
    • Prefer using CSS classes over inline styles for better maintainability.
   <!-- Good -->
   <div class="item">{{ item.name }}</div>

   <style scoped>
   .item {
     color: red;
   }
   </style>

   <!-- Bad -->
   <div :style="{ color: 'red' }">{{ item.name }}</div>
Copy after login

Component Practices

  1. Component Reusability:
    • Design components to be reusable and configurable through props.
   // Good
   <BaseButton :label="buttonLabel" :disabled="isDisabled" @click="handleClick" />

   // Bad
   <button :disabled="isDisabled" @click="handleClick">{{ buttonLabel }}</button>
Copy after login
  1. Prop Validation:
    • Always validate props using type and required attributes.
   // Good
   props: {
     title: {
       type: String,
       required: true
     },
     age: {
       type: Number,
       default: 0
     }
   }

   // Bad
   props: {
     title: String,
     age: Number
   }
Copy after login
  1. Avoid Long Methods:
    • Break down long methods into smaller, more manageable methods.
   // Good
   methods: {
     fetchData() {
       this.fetchUserData();
       this.fetchPostsData();
     },
     async fetchUserData() { ... },
     async fetchPostsData() { ... }
   }

   // Bad
   methods: {
     async fetchData() {
       const userResponse = await fetch('api/user');
       this.user = await userResponse.json();
       const postsResponse = await fetch('api/posts');
       this.posts = await postsResponse.json();
     }
   }
Copy after login
  1. Avoid Computed Properties with Side Effects:
    • Computed properties should be used for pure computations and not for side effects.
   // Good
   computed: {
     fullName() {
       return `${this.firstName} ${this.lastName}`;
     }
   }

   // Bad
   computed: {
     fetchData() {
       // Side effect: fetch data inside a computed property
       this.fetchUserData();
       return this.user;
     }
   }
Copy after login

Template Practices

  1. Use v-show vs v-if:
    • Use v-show for toggling visibility without adding/removing elements from the DOM, and v-if when conditionally rendering elements.
   <!-- Good: Use v-show for toggling visibility -->
   <div v-show="isVisible">Content</div>

   <!-- Good: Use v-if for conditional rendering -->
   <div v-if="isLoaded">Content</div>

   <!-- Bad: Use v-if for simple visibility toggling -->
   <div v-if="isVisible">Content</div>
Copy after login
  1. Avoid Large Templates:
    • Keep templates clean and small; break them into smaller components if they become too large.
   <!-- Good: Small, focused template -->
   <template>
     <div>
       <BaseHeader />
       <BaseContent />
       <BaseFooter />
     </div>
   </template>

   <!-- Bad: Large, monolithic template -->
   <template>
     <div>
       <header>...</header>
       <main>...</main>
       <footer>...</footer>
     </div>
   </template>
Copy after login

State Management Practices

  1. Use Vuex for State Management:
    • Use Vuex for managing complex state across multiple components.
   // Good
   // store.js
   export default new Vuex.Store({
     state: { user: {} },
     mutations: {
       setUser(state, user) {
         state.user = user;
       }
     },
     actions: {
       async fetchUser({ commit }) {
         const user = await fetchUserData();
         commit('setUser', user);
       }
     }
   });
Copy after login
  1. Avoid Direct State Mutation in Components:
    • Use mutations to modify Vuex state rather than directly mutating state in components.
   // Good
   methods: {
     updateUser() {
       this.$store.commit('setUser', newUser);
     }
   }

   // Bad
   methods: {
     updateUser() {
       this.$store.state.user = newUser; // Direct mutation
     }
   }
Copy after login

Error Handling and Debugging

  1. Global Error Handling:
    • Use Vue’s global error handler for catching and handling errors.
   Vue.config.errorHandler = function (err, vm, info) {
     console.error('Vue error:', err);
   };
Copy after login
  1. Provide User Feedback:
    • Provide clear feedback to users when an error occurs.
   // Good
   methods: {
     async fetchData() {
       try {
         const data = await fetchData();
         this.data = data;
       } catch (error) {
         this.errorMessage = 'Failed to load data. Please try again.';
       }
     }
   }

   // Bad
   methods: {
     async fetchData() {
       try {
         this.data = await fetchData();
       } catch (error) {
         console.error('Error fetching data:', error);
       }
     }
   }
Copy after login

By adhering to these additional practices, you can further enhance the quality, maintainability, and efficiency of your Vue.js applications.

The above is the detailed content of General Coding Standards for Vue js.. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template