Vue.js Best Practices and Coding Conventions

Adopting best practices and coding conventions is essential for writing clean, maintainable, and efficient code in any programming language or framework. Vue.js is no exception. This chapter will explore the best practices and coding conventions that should be followed when developing applications with Vue.js. From basic concepts to advanced techniques, this chapter will provide a comprehensive guide to ensure your Vue.js code is robust, readable, and scalable.

General Coding Conventions

File and Directory Structure

A well-organized file and directory structure is crucial for maintaining a scalable project. Vue CLI offers a standard structure that can be customized as needed.

Example Structure

				
					src/
├── assets/
├── components/
│   ├── Header.vue
│   ├── Footer.vue
│   └── ...
├── views/
│   ├── Home.vue
│   ├── About.vue
│   └── ...
├── store/
│   ├── index.js
│   └── modules/
├── router/
│   └── index.js
├── App.vue
└── main.js

				
			

Naming Conventions

Components

  • Use PascalCase for component names.
				
					// Correct
components: {
  MyComponent,
}

// Incorrect
components: {
  myComponent,
}

				
			

Files and Directories

  • Use kebab-case for filenames.
				
					// Correct
my-component.vue

// Incorrect
MyComponent.vue

				
			

Vue Component Best Practices

Single File Components (SFCs)

Single File Components (SFCs) encapsulate the template, script, and styles in a single .vue file. This improves readability and maintainability.

Example

				
					<template>
  <div class="example">
    <h1>{{ message }}</h1>
  </div>
</template> <script type="litespeed/javascript">export default{data(){return{message:'Hello, Vue.js!',}},}</script> <style scoped>.example {
  color: blue;
}</style>
				
			

Template Best Practices

  • Use meaningful class and id names.
  • Keep templates simple and avoid complex logic.

Example

				
					<template>
  <div class="user-profile">
    <h2>{{ user.name }}</h2>
    <p>{{ user.bio }}</p>
  </div>
</template>

				
			

Script Best Practices

  • Use ES6 syntax.
  • Keep the logic in the data, computed, methods, watch, and lifecycle hooks sections.

Example

				
					<script type="litespeed/javascript">export default{data(){return{count:0,}},computed:{doubleCount(){return this.count*2},},methods:{increment(){this.count++},},}</script> 
				
			

Style Best Practices

  • Use scoped styles to avoid conflicts.
  • Follow a consistent naming convention for classes.

Example

				
					<style scoped>.button {
  background-color: #42b983;
  color: white;
  padding: 10px;
}</style>
				
			

State Management

Using Vuex Effectively

Vuex is the official state management library for Vue.js. It helps manage the state of your application in a centralized and predictable way.

Example Store

				
					// store/index.js
import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    count: 0,
  },
  mutations: {
    increment(state) {
      state.count++;
    },
  },
  actions: {
    increment({ commit }) {
      commit('increment');
    },
  },
  getters: {
    doubleCount: (state) => state.count * 2,
  },
});

				
			

Handling State in Components

Example

				
					<template>
  <div>
    <p>{{ count }}</p>
    <button @click="increment">Increment</button>
  </div>
</template> <script type="litespeed/javascript">import{mapState,mapActions}from 'vuex';export default{computed:{...mapState(['count']),},methods:{...mapActions(['increment']),},}</script> 
				
			

Reusability and Composition

Mixins

Mixins are a flexible way to distribute reusable functionalities for Vue components.

Example

				
					// mixins/hello.js
export const helloMixin = {
  created() {
    console.log('Hello from mixin!');
  },
};

				
			
				
					<script type="litespeed/javascript">import{helloMixin}from './mixins/hello';export default{mixins:[helloMixin],}</script> 
				
			

Custom Directives

Custom directives extend Vue’s functionality by adding custom behavior to DOM elements.

Example

				
					// directives/v-focus.js
export default {
  inserted(el) {
    el.focus();
  },
};

				
			
				
					<template>
  <input v-focus />
</template> <script type="litespeed/javascript">import vFocus from './directives/v-focus';export default{directives:{focus:vFocus,},}</script> 
				
			

Filters

Filters are used to format data in the template.

Example

				
					// filters/capitalize.js
export function capitalize(value) {
  if (!value) return '';
  value = value.toString();
  return value.charAt(0).toUpperCase() + value.slice(1);
}

				
			
				
					<template>
  <p>{{ message | capitalize }}</p>
</template> <script type="litespeed/javascript">import{capitalize}from './filters/capitalize';export default{filters:{capitalize,},data(){return{message:'hello world',}},}</script> 
				
			

Slots

Slots are used to create flexible and reusable components.

Example

				
					<template>
  <div class="card">
    <slot name="header"></slot>
    <slot></slot>
    <slot name="footer"></slot>
  </div>
</template>

				
			
				
					<template>
  <Card>
    <template v-slot:header>
      <h1>Header Content</h1>
    </template>
    <p>Main Content</p>
    <template v-slot:footer>
      <p>Footer Content</p>
    </template>
  </Card>
</template> <script type="litespeed/javascript">import Card from './components/Card';export default{components:{Card,},}</script> 
				
			

Performance Optimization

Lazy Loading

Lazy loading allows you to load components only when they are needed.

Example

				
					Lazy Loading
Lazy loading allows you to load components only when they are needed.

Example
				
			

Code Splitting

Code splitting breaks your application into smaller chunks that can be loaded on demand.

Example

Vue CLI handles code splitting automatically with webpack when you use dynamic imports.

Optimizing Re-renders

Minimize re-renders by using computed properties and avoiding unnecessary watchers.

Example

				
					<template>
  <div>{{ doubleCount }}</div>
</template> <script type="litespeed/javascript">export default{data(){return{count:0,}},computed:{doubleCount(){return this.count*2},},}</script> 
				
			

Testing

Unit Testing with Vue Test Utils

Vue Test Utils is the official library for unit testing Vue components.

Example

				
					import { mount } from '@vue/test-utils';
import Counter from './Counter.vue';

describe('Counter.vue', () => {
  it('increments count when button is clicked', () => {
    const wrapper = mount(Counter);
    wrapper.find('button').trigger('click');
    expect(wrapper.vm.count).toBe(1);
  });
});

				
			

Security Best Practices

Preventing XSS

Always escape user input and avoid using v-html to prevent cross-site scripting (XSS) attacks.

Example

				
					<template>
  <div>{{ message }}</div>
</template> <script type="litespeed/javascript">export default{data(){return{message:'<script>alert("XSS Attack")</script>',
    };
  },
};
</script>

				
			

Handling User Input Safely

Use libraries like sanitize-html to sanitize user input.

Example

				
					import sanitizeHtml from 'sanitize-html';

export default {
  methods: {
    sanitize(input) {
      return sanitizeHtml(input);
    },
  },
};

				
			

Following best practices and coding conventions in Vue.js ensures that your code is clean, maintainable, and scalable. By adhering to these guidelines, you can create high-quality applications that are easy to understand and maintain. From general coding conventions to performance optimization and security best practices, this chapter has covered a wide range of topics to help you become a better Vue.js developer. Happy coding !❤️

Table of Contents