Best Practices for Writing Vue.js

2486 VIEWS

While Vue.js is a JavaScript framework for creating user interfaces, there are several best practices for writing Vue.js that every beginner or advanced developer should follow. Following these best practices will ensure that you create effective Vue.js code that improves readability and quality. Many miss these rules when coding, and some people are unaware of them, which is why we’ve put together a list of them in this post.

The list below comprises some of the most prevalent recommended best practices for writing Vue.js code and making it more clean, understandable, and improving your expertise level.

  1. Use Kebab or Pascal Case to create Component
  2. Avoid using v-if with v-for Elements
  3. Use Computed property for filtering
  4. Always use the  : key attribute with v-for
  5. Use kebab case to name an event
  6. Component data must return function
  7. Use camelcase for Prop name casing
  8. Scoping component style

Use Kebab or Pascal Case to Create a Component

When creating a component in Vue.js, you should use a pascal or kebab case. Vue.js, on the other hand, advocates using a Pascal case in single-file components and strings. Because Vue components have instances, it makes it reasonable to utilize PascalCase as well. Using PascalCase within JSX (and templates) makes it easier for code readers to differentiate between components and HTML elements. Additionally, with PascalCase, you can also autocomplete your component names because JavaScript uses them.

Example of Pascal case for single-file components and string templates:

<SearchButton/>

Example of kebab case for single-file components and string templates:

<search-button><search-button/>

Avoid Using v-if with v-for Elements

While it can be very tempting to use the v-if on the same element as v-for to filter out data when working with conditional rendering. It’s a terrible practice, and Vue.js prefers the v-for directive over the v-if directive. So it goes over all of the elements and then verifies the v-if conditional.

This means that we’ll have to cycle through the full array even if we only want to render a few things from a list. To avoid a situation like this see the code example below.

Instead of this: 

<ul> <li v-for="list in lists" v-if="showActiveList" :key="list.id" > {{ list.category }} </li> </ul>

Code this:

<ul> <li v-for="list in lists" :key="list.id" > {{ list.category }} </li> </ul>

Use the Computed Property for Filtering Data

It is ideal to use the computed property whenever you want to filter or transform your data, typically you will use a computed value for that purpose.

Here is an example: 

<script>
export default {
  name: 'WebMaterials',
 data: {
            language: '',
            materials: [
                { title: "Eloquent Javascript", author: 'Accessories' language: 'JS'},
      { title: "You don't know JS", author: 'Kyle Simpson' language: 'JS' },
      { title: "CSS Optimization Basics", author: 'Jens Oliver' language: 'CSS'},
 { title: "The HTML Handbook", author: 'Flavio Copes' language: 'HTML'},
         
],
computed: {
            filterMaterialsByLanguage: function(){
                return this.materials.filter(product => !material.language.indexOf(this.language))
            }
        }
    });
}
</script>

Computed properties are cached based on their reactive dependencies. As a result, it will only re-evaluate when some of its reactive dependencies have changed.

Always Use the : key Attribute with v-for

It is very necessary to use the :key attribute with v-for because the virtual DOM in VueJs creates vnodes on each of the listed items so if the :key attribute is not included in the list item when using v-for. The virtual DOM will have a hard time detecting any changes, or to identify any changes  for a specific list item.

<div v-for="item in items" :key="item.id">
 {{ item.value }}
</div>

Using the key attributes helps Vue to delete or update components within the loop. When comparing the new list of nodes against the old list, the :key attribute is utilized as an identifier for the virtual DOM algorithm to identify vnodes.

You can read more about :key attributes on Vue.js doc

Use a Kebab Case to Name an Event

When working, emitting, or listening to events in Vue.js it is a good practice to use a kebab case for event names, because of “HTML attribute case-insensitivity”. For example, if we use clickEvent it will automatically be converted to a lowercase click-event which will be difficult for the clickEvent to listen to. below is an example of using a kebab case for event names

<template>
  <button @click="$emit('click-event')" />

</template>
<script>
export default {
  methods: {
    onClick () {
      this.$emit('click-event')

      /
    }
  }
}
</script>

Component Data Must be a Function

Vue.js recommends that each instance of a component should have its own data object. Because Vue components are static and if we don’t do that, all instances will be sharing the same object, and every time we change something, it will reflect in all other instances. for example:

data: {
firstName: 'Ezekiel' 
lastName: 'Lawson' 
}

In the above example, if we intend to use the firstName, and lastName property from a different place in our component and change the value of it, it will be reflected in all the places because we are using an object and every instance of the component references the same data object, so if we change the firstName or lastName it will also change the name of every other part

Here is the best solution:

export default {
 data () { 
return { firstName: 'Ezekiel' ,
lastName: 'Lawson' }
 }
 }

Use Camelcase for Prop Name Casing

When naming your props in Vue.js you must use a camel case during declaration and a kebab case when working with templates. Let’s check out a code example.

<Helloworld send-message="Welcome to your Vue JS Application"/>
props: {
  sendMessage: String
}

Scoping Component Style

When working with styles in your application, the styles in your App component should be global and the rest styles in other components should be scoped. The reason is if you apply changes to a particular class in a different component and other components have that same class name, the changes will reflect globally. So the best solution to this problem is to scope your style. Let’s look at an example of scoped style: 

<template>
 <h1 class="heading-text">WELCOME TO MY BLOG</h1>
 </template>
 <!-- No scoped attribute →
 <style> .heading-text { font-size: 20px; font-weight: bold; } 
</style>

In the code example above, I made my styling a global styling on the APP component, because I want another heading in a different component with the class “heading-text” to have one styling.

<template> 
<h1 class="heading-text">WELCOME TO MY BLOG</h1> 
</template>
<input type="text" class="search-btn" placeholder="Search items">
 <!-- scoped attribute example --> 
<style scoped> .button-close { background-color: red; border: none; border-radius: 4px solid gray; }
 </style>

Conclusion

There are a couple of other  practices to follow when writing Vue.js, but these are the handpicked ones. Hopefully, this article will help you write efficient code in Vue.js by following all of the listed practices.

If you would like to learn more about Vue.js, take a look at this article, “Understanding GET and POST method in Vue.js.”


I am a software developer with development experience in frontend building responsive website sites using these web technologies like Javascript, VueJs, HTML and CSS, Bootstrap Tailwind CSS. I specialize in converting designs to Code, and I love teaching and sharing my technical ideas through an article.


Discussion

Click on a tab to select how you'd like to leave your comment

Leave a Comment

Your email address will not be published.

Menu
Skip to toolbar