Showing posts with label vue.js development. Show all posts
Showing posts with label vue.js development. Show all posts

Tuesday, March 30, 2021

Top 11 Best Practices For Vue.js Development

 

Top 11 Best Practices For Vue.js Development

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.

Final Words-

These are some of the best practices for vue.js development. There can be some others too. You can build effective applications by using these best practices. If you are facing any difficulties while using vue.js for development, consult with Solace experts. We are here to help you through consultation and development. You can also hire vue.js developers of solace team for successful development of applications. Connect with Solace and get a free quote for development. We will be happy to help you.


Tuesday, November 19, 2019

5 Best Development Tools For Vue.js



In 2014, Vue.js developed to compete in a space essentially dominated by Angular and React. Quick forward to 2018, and Vue had gathered a greater number of stars on Github than the last mentioned. Despite the fact that star check doesn’t infer use, it somewhat signifies interest, which, for Vue’s case, is very reasonable, thinking about its power yet relative simplicity. You can compare Vue with Angular and React at- Angular vs. React vs. Vue: A 2019 Comparison (Updated).
While Vue is without a doubt a delight to work with, it’s sometimes important for developers to deploy certain extra tools to help get them up to speed with the framework and effectively build applications with it. This article reveals five tools to do only that.

5 Best Development Tools For Vue.js-

1. Vue loader and Vue CLI-

Vue- loader-

It is a loader for webpack that enables you to author Vue components in a format called Single-File Components (SFCs). The combination of webpack and vue- loader gives you a faster workflow for developing your Vue.js applications.
The project provides helpful features, for example, using distinctive webpack loaders for various parts of your components, treating static resources as module dependancies to be dealt with webpack loaders, hot-reloading while preserving states during developments and more.

Vue CLI-



Despite the fact that the “old” Vue-CLI is presently deprecated and Vue-CLI 3 is in RC status, the project provides an interactive project scaffolding with zero config fast prototyping, a runtime dependency (@vue/cli-service) and a full graphical UI to create and manage Vue.js projects.
Composed of a CLI tool, CLI service (built over Webpack) and a plugin system, the project gives out-of-the-box support for Babel, TypeScript, ESLint, PostCSS, PWA, Unit Testing and End- to- end Testing. The plugin system allows you to build and share reusable solutions and the project is configurable without the requirement for ejecting.

2. Vue.js devtools-

As developers, we are fallible and therefore require approaches to track mistakes or anomalies in our application. With regards to Vue applications, Vue.js devtools has demonstrated to be the standard for doing so.
A debugging tool, Vue devtools comes as an extension on various browsers, which enables you to effortlessly debug Vue code by essentially accessing the site page that harbors it.
After installing the Vue devtools extension on your browser, you’ll discover a Vue icon close to your search bar. The icon lightens up or blurs to signify this.
To make your Vue code debuggable with Vue devtools, you must grant the latter express permission from your code, utilizing Vue.config.devtools = true. At the point when done, a Vue tab on your browser developer menu will be unveiled.
Basically, Vue devtools strips down your Vue application into its core essentialities to give you insight into what’s happening at each step. You’ll have the option to see your enabled Vue components and the data (and their state) in them; the states defined in your Vuex store and the mutations triggered; the performance of your application; and other things.

3. StoryBook-



Although mostly mentioned with regards to React, with the release of Storybook 3.2 it currently supports the same helpful workflow for Vue components. StoryBook gives a rapid UI component development that empowers you to explore a component library, navigate and view UI components in a real-time web development environment with hot- reload.
Through StoryBook you can develop components quicker in isolation from your application, empowering reusability. StoryBook can also combined with Bit to rapidly prototype and develop components in different projects. You can likewise attempt these helpful addons: addon-actions, addon-links, addon-knobs, addon-notes.

4. Nuxt.js-



To understand Nuxt.js, we should initially understand the requirement for it. Most importantly, Nuxt is a giant leap towards accomplishing server-side rendering (SSR) on Vue applications. To comprehend why SSR is a concern, how about we quickly address why Client Side Rendering isn’t always desirable.
Utilizing client- side rendering, we (developers and users) are at the mercy of the client (our browser) to fetch, initially manipulate, and render data. Hence, there is constantly a lag between a page’s load time and the time needed to fetch and display necessary information. Other than this process being inconvenient to user experience — particularly for slow connections — it is additionally troublesome for SEO since crawlers aren’t ready to index content after crawling a website page.
Nuxt can hence be viewed as the official execution tool for solving, in addition to other things, the inadequacies of client side rendering on Vue. This article does equity to assessing how Nuxt competently handles SSR.
Nuxt is likewise generally known for static site generation, which is simply an astounding value proposition. In this capacity, Nuxt allows to build static website pages with no need to deploy a server. It handles this in an especially basic way and makes routing a simply. Nuxt can also serve as a framework for building lightweight SPAs. In an upcoming article, I’ll take you through the process of investigating Nuxt by building a functional website.

5. Vue- dummy-

While there are other development tools fit for this spot, vue-dummy is one of my top choices. Basically, vue- dummy is a library that provides our application with placeholder text and images. It simplifies the way toward producing this placeholder content to the point that we could nearly take it for granted.
To use it, we’ll start by installing the library using npm or simply adding a link to our HTML page:
npm install vue-dummy --save-dev
Or:
<script src="https://unpkg.com/vue-dummy"></script>
Once complete, we can explicitly state our intention of using vue-dummy:
Vue.use(VueDummy)
We can now be able to utilize the vue-dummy order to render placeholder text. For instance, to add placeholder Lorem ipsum text of 300 words, we simply write something like this:
<p v-dummy="300"></p>
Similarly, we’ll use <img /> to generate a 200×200 placeholder image.
As recently expressed, it’s not difficult to take for granted the usefulness of vue-dummy. We find it as of extraordinary assistance whenever we were developing a web application with, say, a Python backend and in this way can’t take advantage of webpack’s hot reloading to instantaneously view how changes to our frontend code affect the general appearance of the interface. Regardless of whether you’re developing a static or dynamic web application, vue- dummy is a tool that will always cut it for rapidly developing Vue applications.

Final Words-

We have listed out these best tools for vue.js development. There may be some others also that you can use. Choosing the best one among them is tricky task. Selection of best one is depend on your development requirement.
Are you confused to choose the best development tool for your vue.js development? Then you might need some help getting started. Solace experts are here to help you with their best knowledge. Connect with experts to consult for best development tool and also for development..