Go Back

Tips and Best Practices for Vue Projects

Tips and Best Practices for Vue Projects
Posted by
Madhavi G
Nov 25 2022

In today’s fast-paced world where the concept of ‘time is money has become the motto of most, everyone wants the best-optimized process to make their work faster and easier. Vue is a swiftly maturing and advanced framework for crafting user interfaces.

Vue has now turned into one of the best JavaScript frameworks with the most stars on GitHub. Here are some of the Vue tips that will help you with everyday development and assist in making your work easier.

But before we directly jump into some time saving tips for Vue, let us look at exactly what it is and then explore the valuable tricks and tips to enhance a Vue project at hand. Also, note that some of the examples shown here are simplified to meet the blog post’s purposes.

What is Vue?

Vue (pronounced as vju or view) is a JavaScript framework for building user interfaces. It is used to build on top of standard HTML, CSS, and JS and provides a declarative and component-based programming model that helps developers create simple or complex interfaces for customers.

Here’s a small example:

import { createApp } from 'vue'
 
createApp({
  data() {
    return {
      count: 0
    }
  }
}).mount('#app')  

With this example, we can see two distinct features of Vue.JS:

1) Declarative Rendering – extending standard HTML with template syntax that allows users to describe HTML output based on the JavaScript state.

2) Reactivity – Automatically tracks JS state changes and efficiently updates the DOM when any changes occur.
Source:- https://vuejs.org/guide

What is Vue JS used for?

Vue JS is used to primarily build web interfaces and single page applications. It can also be used to both desktop and mobile app development due to the HTML extensions and JavaScript base working in tandem with the Electron framework. It is because of this that Vue JS is one of the most heavily favored front end tools especially for developers.

Now that we know what Vue is, let’s look at some tips For Vue.js Developers.

Top 10 Vue.JS best practices for Developers

  1. Quotes to watch nested values:
    You can without any trouble watch nested values merely by utilizing quotes.For example:

    watch {
            ‘$route.params.id’() {
                //
    }
        }
    

    This is perfect when working with deeply nested objects on Vue.

  2. V-if VS V-Show:
    In some cases and scenarios, it is better to use v-show instead of v-if:

    <ComplicatedChart v-show= "chartEnabled"/>

    Using v-if helps create and destroy elements when switched on or off, whereas v-show creates the elements and hides them by styling them as a display. Doing this can make your code more competent, especially when toggling is more expensive to render. On the flip side, if you do not need that component immediately, it is better to use v-if to skip rendering and helps pages load faster.

  3. Selectors can override the styles of child components:
    Scoped CSS is the best way to keep things neat and not leach the styles of the component into other parts of the app. But in some cases, Vue.js app improvement needs to be put aside to cover the requirements, and overriding the style is the best solution.

    The deep selector is perfect to implement this:

    <style scoped>
            .parent-class >>> .child-class{
                .font-weight: 600;
    }
        </style>
    

    For Sass in Vue2:

    <style scoped>
            ::v-deep .child-class{
                .font-weight: 600;
    }
        </style>
    

    For Sass in Vue3::

    <style scoped>
            :deep(.child-class){
                .font-weight: 600;
    }
        </style>
    

    In case you are using a CSS pre-processor like SCSS, you may have to use /deep/ instead.
    Also Read:- React vs Vue

  4. Pseudo-class creation for slot styling:
    For specific components with a the pseudo-class slots are used to enable styling options for the previously mentioned slot content. By default, the scope styles do not affect content rendered by as they are owned by the parent component passing them in. For example,

    <style scoped>
    :slotted(.slot-class){
        font-weight: 600;
    }	
    </style>
    
  5. Deeply watching arrays and objects:
    As watchers, the trick’s part for arrays or objects is not triggered properly and to improve watcher performance, set ‘deep’ to truly watch the content added inside. Let’s take the example of:

    export default {
      name: 'DetailPage",
      props: {
        product: {
          type: Object,
          required: true,
        },
      },
      watch: {
        product: {
          // to look inside the object
          deep: true,
     
          //move the method to a handler field
          handler()
            //;
          }
        }
      }
    }
    
  6. rouping using the Template tag:
    The template tag can be used to organize your code better. You can use it to simplify v-if logic or v-for logic as well. Let us take the example of using the v-if condition multiple times:

    <template>
      <div class="card">
        <img src= "imgPath"/>
        <h3>
          {{ title }}
        </h3>
        <h4 v-if="expanded">
          {{ subheading }}
        </h4>
        <div
          v-if= "expanded"
          class= "card-content"
        >
          <slot />
        </div>
        <SocialShare v-if= "expanded"/>
      </div>
    </template>
    

    This may be a bit too much, and in the first look, we see that a group of elements is being hidden or shown together. But this can be fixed by grouping the template tag.

    Using the template tag when you need to make a couple of elements that need to be hidden or displayed together. This will keep the template codes organized and simplified. Use the v-if, v-show, and v-for, etc. logic in this tag.

     <template v-if=”condition”>
        <h3>{{ product name }}</h3>
        <p><strong>{{ product price}}</strong></p>
        <p>{{ product description }}</p>
    </template>  
    
  7. Validate plugin for Form Validation:
    The Validate plugin is a simple, model-based validation library used for advanced Vue.js practices. It allows developers to simplify the structure for the dynamic validation of rules. These rules can be added to a validation object in the component definition instead of adding them directly into the input elements in the DOM.

    This also supports nested models, collection validation, and function composition. If you want to better explore the Vuelidate plugin, then you can refer to the Vuelidate documentation.

    To validate your form, in the script section of your app.vue file, you can add the following:

    <script>
    import { required, minLength, between } from 'vuelidate/lib/validators'
    export default {
      name: 'app',
      data() {
        return {
          name: ",
          password: ",
          age:"
        }
      },
      validations: {
        name: {
          required,
          minLength: minLength(4)
        },
        password: {
          required,
          minLength: minLength(4)
        },
        age: {
          required,
          between: between(18,45)
        }
      }
    }
    </script>
    
  8. Custom delimiters:
    When using double curly brackets “{{}}” in your HTML files and templates, there is a chance of confusion and conflict arising with other engines used. The best way to reduce this is by changing the delimiters. Just add the delimiters instead as an option as optimized tips for your Vue apps.

    For example, you could use the code:

    new Vue({
        el: '#app',
        data: data,
        delimiters: ["[[","]]"]
    });
    
  9. Mentioning specific prop types:
    The best way to restrict a prop to a specific set of values is by using the validator option.

    export default {
      name: 'Image',
      props: {
        src: {
          type: String,
        },
        style: {
          type: String,
          validator: s => ['square', 'rounded'].includes(s)
        }
      }
    };
     
    

    This validator function takes the prop and returns one of two results – true or false. Thai shows if the prop is valid. Some of the most common areas to use are alert types, buttons, and colors.

  10. Handling warnings and errors:
    If you want to handle warnings and errors better, then add custom handlers to help improve user experience.

    // Vue 3
    const app = createApp(App);
    app.config.errorHandler = (err) => {
      alert(err);
    };
     
    // Vue 2
    Vue.config.errorHandler = (err) => {
      alert(err);
    };
    

    Bug tracking apps like Rollbar and Bugsnag hook these handlers to log errors, but you can use them faster and easier with Vue Js. In Vue 3, the error handler only shows up as a template and watches the errors, but in Vue 2, it catches everything.

    Crafting apps in Vue is straightforward as such, however, if you want to develop superior quality applications, you are up for a big contest. These tips will not make your app picture-perfect, but leveraging them will swiftly enhance the value of your programming.

Moving Forward

We hope our optimize tips for your Vue apps will help you in your development journey. Achieving the best front-end performance is more important than you realize. It is the first view a potential customer has of your brand and your business. Developers have much faster and much better computers than normal users who will actually end up using your website or app.

In fact, your users may not even access it through their computers but via outdated phones. So, when using Vue to create websites, you need to do the best in your power to deliver optimal experiences across all platforms.

Vue JS is a powerful and easy-to-learn javaScript framework and you will need to hire Vue.js Developers to implement the best practices. It does not need much effort to be understood, and the documentation provided with Vue is thorough enough for beginners as well.

Our list of tips and tricks to help build Vue JS apps and projects will help smoothen things through. So, if you found this blog’s information useful, please share it with others and let us know your favorite tip to improvise Vue projects.

We at Technostacks, top Vue JS development company, have an expertise in developing Vue.js apps. If you are planning to implement the best practices for Vue or want to develop a Vue.js based application then contact us. We will assist you the best solution for your project requirements.

X