Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for General Coding Standards for Vue js.
Dharmendra Kumar
Dharmendra Kumar

Posted on

     

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.
// GoodconstMAX_ITEMS=10;functionaddItem(item){if(items.length<MAX_ITEMS){items.push(item);}}// BadfunctionaddItem(item){if(items.length<10){items.push(item);}}
Enter fullscreen modeExit fullscreen mode
  1. Usev-for Efficiently:
    • When usingv-for, always provide a uniquekey to optimize rendering.
<!-- Good --><divv-for="item in items":key="item.id">     {{ item.name }}</div><!-- Bad --><divv-for="item in items">     {{ item.name }}</div>
Enter fullscreen modeExit fullscreen mode
  1. Avoid Inline Styles:
    • Prefer using CSS classes over inline styles for better maintainability.
<!-- Good --><divclass="item">{{ item.name }}</div><stylescoped>.item{color:red;}</style><!-- Bad --><div:style="{ color: 'red' }">{{ item.name }}</div>
Enter fullscreen modeExit fullscreen mode

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>
Enter fullscreen modeExit fullscreen mode
  1. Prop Validation:
    • Always validate props using type and required attributes.
// Goodprops:{title:{type:String,required:true},age:{type:Number,default:0}}// Badprops:{title:String,age:Number}
Enter fullscreen modeExit fullscreen mode
  1. Avoid Long Methods:
    • Break down long methods into smaller, more manageable methods.
// Goodmethods:{fetchData(){this.fetchUserData();this.fetchPostsData();},asyncfetchUserData(){...},asyncfetchPostsData(){...}}// Badmethods:{asyncfetchData(){constuserResponse=awaitfetch('api/user');this.user=awaituserResponse.json();constpostsResponse=awaitfetch('api/posts');this.posts=awaitpostsResponse.json();}}
Enter fullscreen modeExit fullscreen mode
  1. Avoid Computed Properties with Side Effects:
    • Computed properties should be used for pure computations and not for side effects.
// Goodcomputed:{fullName(){return`${this.firstName}${this.lastName}`;}}// Badcomputed:{fetchData(){// Side effect: fetch data inside a computed propertythis.fetchUserData();returnthis.user;}}
Enter fullscreen modeExit fullscreen mode

Template Practices

  1. Usev-show vsv-if:
    • Usev-show for toggling visibility without adding/removing elements from the DOM, andv-if when conditionally rendering elements.
<!-- Good: Use v-show for toggling visibility --><divv-show="isVisible">Content</div><!-- Good: Use v-if for conditional rendering --><divv-if="isLoaded">Content</div><!-- Bad: Use v-if for simple visibility toggling --><divv-if="isVisible">Content</div>
Enter fullscreen modeExit fullscreen mode
  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>
Enter fullscreen modeExit fullscreen mode

State Management Practices

  1. Use Vuex for State Management:
    • Use Vuex for managing complex state across multiple components.
// Good// store.jsexportdefaultnewVuex.Store({state:{user:{}},mutations:{setUser(state,user){state.user=user;}},actions:{asyncfetchUser({commit}){constuser=awaitfetchUserData();commit('setUser',user);}}});
Enter fullscreen modeExit fullscreen mode
  1. Avoid Direct State Mutation in Components:
    • Use mutations to modify Vuex state rather than directly mutating state in components.
// Goodmethods:{updateUser(){this.$store.commit('setUser',newUser);}}// Badmethods:{updateUser(){this.$store.state.user=newUser;// Direct mutation}}
Enter fullscreen modeExit fullscreen mode

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);};
Enter fullscreen modeExit fullscreen mode
  1. Provide User Feedback:
    • Provide clear feedback to users when an error occurs.
// Goodmethods:{asyncfetchData(){try{constdata=awaitfetchData();this.data=data;}catch(error){this.errorMessage='Failed to load data. Please try again.';}}}// Badmethods:{asyncfetchData(){try{this.data=awaitfetchData();}catch(error){console.error('Error fetching data:',error);}}}
Enter fullscreen modeExit fullscreen mode

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

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

⚡I’m a curious coder who loves building things! Whether it’s creating beautiful website designs or making sure the behind-the-scenes stuff runs smoothly, I’m all in. Let’s turn code into magic! ⚡
  • Location
    Bihar- Bettiah
  • Education
    BE
  • Work
    Software Engineer at Qualminds
  • Joined

More fromDharmendra Kumar

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp