Wednesday, February 10, 2021

Vue JS — Best Practices

 Vue JS Logo

VueJS — The Progressive JavaScript Framework

Vue (pronounced /vjuː/, like view) is a progressive framework for building user interfaces. Unlike other monolithic frameworks, Vue is designed from the ground up to be incrementally adoptable. The core library is focused on the view layer only, and is easy to pick up and integrate with other libraries or existing projects. On the other hand, Vue is also perfectly capable of powering sophisticated Single-Page Applications when used in combination with modern tooling and supporting libraries.

If you are an experienced frontend developer and want to know how Vue compares to other libraries/frameworks, check out the Comparison with other Frameworks.

Lifecycle Hooks

Every Vue instance goes through a series of initialisation steps. When it is created from setting up data observation to compiling the template, to mounting the instance to the DOM, and finally to updating the DOM during data changes. This process is known as the lifecycle of a Vue instance and they have some functions run inside them by default as they go through this process of creating and updating the DOM. It is inside them that Vue components are created and manipulated, these functions are called lifecycle hooks.

There are eight lifecycle methods:

  1. Before Create
  2. Created
  3. Before Mount
  4. Mounted
  5. Before Update
  6. Updated
  7. Before Destroy
  8. Destroyed

If interested, take a look at  the Lifecycle Diagram of Vue JS. Refer to the official page which has complete details about each lifecycle hooks.

Be Aware of Camel vs Kebab Case

JavaScript are case-sensitive aka Counter is not equal to counter. As HTML, in general is case-insensitive, especially the HTML attributes. As VueJS spans both of these worlds, it’s better to understand this clearly.

camelCase

Start with lower-case and combine subsequent words by capitalise them. Example: amInCamelCase.

kebab-case

Write everything in lower-case and separate words by hyphens. Example: this-is-a-kebab-case.

To help you out, VueJS translates camelCase prop names into kebab-cased equivalent. But whenever things happen automatically, you need to be aware of it.

Vue.component('my-component', {
  props: ['myPropertyMessage'], // camelCase in JavaScript
  template: '<h1>{{myPropertyMessage}}</h1>'
})

The above JS code will translate to something like below

<!-- kebab-case in HTML -->
<my-component my-property-message="Hello World!"></my-component>

Hence declare props with camelCase and use Kebab Case in Templates.

Always use kebab-case for event names

When emitting/listening to custom events, we should always use kebab-case. Why? Because the events will be transformed automatically into lowercase anyway. We wont be listening to an event in camelCase or PascalCase, therefore, makes more sense to declare the event the same way we are going to listen to it: in kebab-case.

// Emitting
this.$emit('my-event') // instead of myEvent

// Listening
v-on:my-event

Always use :key in v-for loops

Is a common best practice to always add a :key to your template loops. A v-for without a :key can lead to hard to find errors, especially with certain kind of components or objects.

Don’t use v-if With v-for Elements

It’s a clear advice from the style guide from vuejs.org

<div v-for='plan in subscriptionPlans' v-if='plan.type == 1'></div>

The reason is that VueJS assigns a higher priority of the v-for than the v-if. This leads to a performance issue as the loop would run and filter inside instead of filter first.

The best practice here is to reduce the size to iterate over before the iteration by using a computed property:

computed: {
  onSaleSubscriptions: function() {
    return this.subscriptionPlans.filter(function (plan) {
       return(plan.type == 1)
    })
  }
}

Use $_ for mixins properties

Mixins are a great way to get repeated code into one single block and import it as many times as you want, but this can lead to several issues. In this point we will address the issue of overlapping properties.

When we import a mixin into our Component we are merging the mixin code with our component code. Now what happens with property that have the same name? Component will always have the upper hand as their properties have higher priority.

What if I want my mixin to have more priority? You can’t assign a priority but you can avoid properties from overlapping or even from overwriting by choosing a correct naming convention.

In order to differentiate mixin properties from Component properties we use $_. Why these symbols? Well, several reasons:
  • Convention from VueJs style guide
  • _ is reserved for Vue’s private properties
  • $ is reserved for Vue’s ecosystem

var authMixin = {
   //...
   methods: {
      $_authMixinGetUserInfo(){
         //...
      }
   }
}

Clear event listeners on component destroy with $off

When listening to events with $on, we should always remember to remove that listener with $off on destroyed(). This prevents us from having memory leaks.

const EmployeeComponent = { 
  mounted() {
    console.log("Employee component mounted");
    this.notify.$on("manager", this.startedListening);
  },
  beforeDestroy() {
    console.log("Employee component before destroy");
    // Remove all listening events.
    this.notify.$off("manager", this.stoppedListening);
  },
  methods: {
    startedListening() {
      // callback
    },
    stoppedListening() {
      // callback
    },
  },
};

Sources:


Tags: , , ,
Location: Bengaluru, Karnataka, India

0 comments:

Post a Comment

Featured Post

Benefits & Best Practices of Code Review

Photo by Bochelly Code reviews are methodical assessments of code designed to identify bugs, increase code quality, and help developers lear...