Top
vue.js best practices

Top 10 Vus.js Best Practices

Vue.js is a powerful open source JavaScript framework for building interfaces and fully capable of creating single page applications.

One can create rich applications using this language. You may mix your codes with Vue.js for better efficiency. Due to its lightweight, Vue.js has advantages over frameworks like Angular and React. 

Apart from allowing one to write faster, it has outstanding community support, a huge library, and is super convenient to use as Vue JS is the easiest front end framework out there among the others JavaScript frameworks. 

So, what are the best practices we like to follow for better results?

1. We should use data property on a component as a function which returns an object rather than data property as a simple object. When the value of data is an object, it’s shared across all instances of a component. 

data: {

  title:

}

Here if you want to use the title property from different places of a component and somewhere you have changed the value of it, it will be reflected all the places of the component as you are using an object and every instance of the component references the same data object, changing the title from one portion will also change the title of every other portion.

You should use data property as a function so that every part of the component gets a different instance of the data property.

data: function () {

  return {

  title:

 }

}

2. Always try to use kebab-case while writing any custom event name as event names are automatically changed to kebab-case internally if we don’t provide it in kebab-case. Here is an example of data sharing between parent & child component:

Child:

<button v-on:click=“$emit(‘increase-count’, 1)”>

 Increment

</button>

Parent html:

<counter

 …

 v-on:increase-count=“increaseCounter”

></counter>

Parent js:

methods: {

 increaseCounter: function (count) {

  this.value += count

 }

}

Related read: The Unavoidable Desktop Application with Vue JS

3. Always use :key attribute with a v-for directive. This attribute is used to check the uniqueness of each of the list items. Vue’s virtual DOM creates VNodes on each of the items of a list. So if there is no key attribute in the list items then Virtual DOM will not identify each of the items separately. So it will be difficult for the virtual DOM to detect any changes for a particular list item.

<div v-for=“item in items” :key=“item.id”>

 {{ item.value }}

</div>

4. Always use a unique id other than index of the array for the value of :key attribute. As you know, arrays are mutable and the index of any item can be changed while adding or removing item from the array. 

<div v-for=“item in items” :key=“item.id”>

 {{ item.value }}

</div>

5. We should not use v-if with v-for as v-for has a higher priority than v-if. See the following example:

<ul>

  <li

 v-for=“car in cars”

 v-if=“car.isActive”

 :key=“car.id”

 >

 {{ car.model }}

  </li>

</ul>

In this case the loop will be iterated over all the items in the list and then it will check the v-if condition. So this is not a good practice.

Instead of this we can compute the list before rendering so that only active cars will be there to iterate.

<ul>

  <li

 v-for=“car in activeCars”

 v-if=“car.isActive”

 :key=“car.id”

 >

 {{ car.model }}

  </li>

</ul>

 

computed: {

  activeCars: function () {

  return this.cars.filter(function (car) {

  return car.isActive

 })

 }

}

Related read: Top 10 Best Practices of Angular JS 1.X

6. It is better to use computed properties rather than using method invocation for any data changes.

computed properties are cached based on their dependencies. A computed property will only re-evaluate when some of its dependencies have changed. 

In comparison, a method invocation will always run the function whenever a re-render happens.

Using computed:

 

var vm = new Vue({
 el: ‘#example’,
 data: {
 firstName: “John”,

 lastName:”Doe”
 },
 computed: {
 setFullName: function () {
 return this.firstName + ‘  ‘ + this.lastName
 }
 }
})

Using methods:

 

methods: {
 setFullName: function () {
 return  this.firstName + ‘  ‘ + this.lastName
 }
}

Related read: Top 10 Laravel Best Practices You Should Follow

 

7.  Never use multiple v-if condition to render multiple consecutive elements. You can use <div> tag to wrap the elements. But it will give an extra element which doesn’t have anything to do. So you can use <template> tag to wrap the elements.

<template v-if=“true”>

 <p>Paragraph 1</p>

 <p>Paragraph 2</p>

 <p>Paragraph 3</p>

</template>

 

8. Use key property if you want to use a reusable element to differentiate between them. Suppose you want to use same element for toggling. If you write something and then toggle to another option the previous text will still be there as you are not using key property to differentiate. If you use key property then it will be blank.

if you allow users to toggle between multiple login types:

<template v-if=“loginType === ‘username'”>

 <label>Username</label>

 <input placeholder=“Enter your username”>

</template>

<template v-else>

 <label>Email</label>

 <input placeholder=“Enter your email address”>

</template>

Then switching the loginType in the code above will not erase what the user has already entered. Since both templates use the same elements, the <input> is not replaced – just its placeholder.

<template v-if=“loginType === ‘username'”>

 <label>Username</label>

 <input placeholder=“Enter your username” key=“username-input”>

</template>

<template v-else>

 <label>Email</label>

 <input placeholder=“Enter your email address” key=“email-input”>

</template>

Now those inputs will be rendered from scratch each time you toggle.

As you know, there are some limitations in Vuejs that Vue cannot detect changes within an array or object.

Array:

When you directly set an item with the index, e.g. vm.values[index] = newValue

There are three solutions to this:

  1. Vue.set(vm.values, index, newValue)
  2. vm.values.splice(index, 1, newValue)
  3. vm.$set(vm.values, index, newValue)

Object:

var vm = new Vue({

 data: {

 profile: {

 firstName: “John”

 }

 }

})

Solution for adding a new property:

  1. Vue.set(vm.profile, ‘lastName’,”Doe”)
  2. vm.$set(vm.profile, ‘lastName’,”Doe”)

Related read: React Native: Top 10 Best Practices We Follow at Innofied

9. We should always use shorthands for directives or we should never use it. That means, we should not mix of using shorthands and the full name of the directives. 

Directive shorthands (: for v-bind:, @ for v-on: and # for v-slot) should be used always or never.

Do you know of any Vue.js best practices that we missed out or you would like to share with us? Do let us know then. 

If you have an app idea that you would like to share with us, talk to our experts. Contact us here. 

Anwita Dhar