Top 11 Best Practices For Vue.js Development

  Solace  Infotech    March 30, 2021    347

 

Vue.js is Javascript open-source front-end building platform to design single-page application. Vue.js developers can use a single file component instance to build rich applications. You can combine the codes with Vue.js for better performance. Vue.js frameworks offers advantages over architectures such as React and Angular because of its lightweight nature and unique framework design principles. Here we’ve curated some of the evolving vue.js best practices. As Vue.js is becoming more and more favourable, these best practices will help you to develop an effortless web app.

You can also know new features and improvements in Vue.js 3.0 at- What’s New In Vuejs 3.0 ?

Top 11 Best Practices For Vue.js Development-

1. Use Data Property On Component-

This is an important Vue.js best practice. You should use data property on a component as a function that returns an object instead of data property as a simple object. When the value of data is object, it’s shared across all instances of component.

data: {
  title: ”
}

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

Use data property as a function so that each part of component gets a different instance of data property.

data: function () {
  return {
  title: ”
 }
}

2. Use Kebab-Case-

You must 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. Let us see 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
 }
}

3. Keep npm Packages Updated-

  • According to the Vue Style guide base components can only contain HTML elements, 3rd party UI components and other some additional based components. 
  • Update npm packages on regular basis to avoid any dependency errors and to use the latest/updated features provided by individual packages.
  • For example, if you have configured vuetify the design patterns in the VueJS project, vuetify regularly updates its packages to provide the best UI with some breaking changes. Hence it is better to update NPN packages regularly to avoid bulky or breaking changes.

npm outdated // run to check outdated npm packages

npx npm-check-updates -u // run to check updates outdated npm packages

npm install // run to update npm packages

4. Manage Global File For Shared Variable –

To make the system more generic and easy to update, manage global configurations(i.e. API URLs. Third party URLs if any, keys can be used in any integrated tool, theme settings) or in a separate file (i.e environment.json). It will help your website to update any global configurations without any re-deployments. 

5. Rule For Directive-

Use key attribute with v-for directive. This attribute is used to check the uniqueness of every list item. Vue’s virtual DOM creates VNodes on every items of a list. Hence if there is no key attribute in the list items then virtual DOM will not identify every item separately. Thus, it will be difficult for the virtual DOM to detect changes for specific list item.

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

6. Rule For V-

You should not use v-if with v-for because v-for has higher priority than v-if. Let us see an example-

<ul>
  <li
 v-for=“car in cars”
 v-if=“car.isActive”
 :key=“car.id”
 >
 {{ car.model }}
  </li>
</ul>

Here, the loop will be iterated over all the items in the list and then it will check the v-if condition. Hence this is not a good practice. Rather than this, we can compute the list before rendering so that just 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
 })
 }
}

7. Use Of Component Properties-

It is good to use computed properties instead of using method invocation for any data changes. Computed properties are cached according to their dependencies. A computed property will just re-evaluate when some of its dependencies have changed. In comparison, method invocation will always run the function when 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
 }
}

8. Used Suitable Data Type Assign For Variable-

  • Use proper data types rather than “any” to minimize the casting time and other casting errors. 
  • Avoid casting inside the loops.
  • For the two data types assigned to the same property, implement type casting by using both the types and conditions.

Example:

 
// Wrong
const age: any = 0; [hard to identify response type at the places this variable used and also hard to track errors on assignments]
 
// Right
const age: number = 0; [easy to track and identify response type]

9. Data Should Always Return Function-

When you declare a Vue component data, that aspect of data should return a value. With other cases, when it does not return an output, that data information will be shared at all instances of component value.

Example:

As per the example below, the functional data is not returning any output. Hence, you cannot access properties outside the data function. It will generate runtime error.

data: {
value: "Vue.js Application",
itemList: [],
counter: 0
 },

Right Way:

data: function () {
return {
value: "Vue.js Application",
itemList: [],
counter: 0
};
  },

10. Clean Code And Refactoring-

  • Use shared/separate file for static functions/properties for reusability. It will help to keep a shared/static code at the same file in entire solution.
  • Make use of tslint or eslint tools for maintaining the code quality
  • In vue, you can decrease the line of code by narrowing the UI into smaller components.
  • Use keywords (Const/Let) provided by typescript smartly rather than var keyword of Javascript.

Example:

Bad Practice:

Var test: number = 0;

“Identifier ‘test’ is never reassigned; use ‘const’ rather than ‘var’

You will get the error as mentioned above if tslint is configured properly when you run the project

Good Practice:

const test: number = 0; // if static, use const
let test: number = 0; // if updateable, use let

11. Use Of Shorthands-

You should always use shorthands for directives or we should never use it. Means you should not mix of using shorthands and full name of the directives. 

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

 


 Article keywords:
vuejs, vue, technology, software

 


 Share this article: 
Print Digg StumbleUpon del.icio.us Facebook Yahoo! Buzz Twitter Google Bookmarks LinkedIn MySpace Orkut PDF Scoopeo Viadeo Add to favorites
      

© Copyright - Articles XP