DEV Community

Cover image for Top 10 Vue.js Tricks You Might Not Know
Muhammadamin
Muhammadamin

Posted on • Edited on

Top 10 Vue.js Tricks You Might Not Know

1. Scoped Slots with v-slot and Dynamic Names

Scoped slots in Vue.js allow you to pass data from a parent component to a child component, enabling greater flexibility and reusability. Did you know you can use dynamic names with scoped slots? Here's an example:

<template>
  <child-component>
    <template v-slot:[dynamicSlotName]="slotProps">
      <!-- Your content here -->
    </template>
  </child-component>
</template>
Enter fullscreen mode Exit fullscreen mode

In this example, dynamicSlotName can be a computed property or a variable that determines the slot name dynamically.

2. Conditional Components with and :is

Vue.js provides the <component> element for rendering dynamic components. You can leverage this feature to conditionally render components based on a variable or computed property:

<template>
  <component :is="componentName"></component>
</template>
Enter fullscreen mode Exit fullscreen mode

Here, componentName represents the name of the component you want to render dynamically.

3. Event Modifiers for Cleaner Code

Vue.js event modifiers allow you to simplify event handling. For example, instead of using event.preventDefault() in your event handler, you can use the .prevent modifier:

<button @click.prevent="submitForm">Submit</button>
Enter fullscreen mode Exit fullscreen mode

Other event modifiers include .stop, .capture, .self, .once, and more.

  1. Async Components for Lazy Loading

Vue.js supports lazy loading of components using async components. This can greatly improve the initial load time of your application. Here's an example:

<template>
  <async-component :is="componentName"></async-component>
</template>

<script>
export default {
  data() {
    return {
      componentName: null
    };
  },
  mounted() {
    import('./AsyncComponent.vue').then(component => {
      this.componentName = component.default;
    });
  }
};
</script>
Enter fullscreen mode Exit fullscreen mode

In this example, AsyncComponent.vue is loaded asynchronously when the component is mounted.

5. Using the Key Attribute for Efficient Re-Render

The key attribute in Vue.js helps optimize rendering by preserving component state. It tells Vue.js to reuse or re-render an existing component instead of creating a new one. Use it when iterating over a list of items:

<template>
  <div>
    <div v-for="item in items" :key="item.id">{{ item.name }}</div>
  </div>
</template>
Enter fullscreen mode Exit fullscreen mode

The :key attribute ensures Vue.js can track and update the elements efficiently.

6. Custom Directives for Enhanced Functionality

Vue.js allows you to create custom directives to extend the functionality of your application. You can define custom directives globally or locally within components. Here's an example of a simple directive that focuses an input field:

<template>
  <input v-focus />
</template>

<script>
export default {
  directives: {
    focus: {
      mounted(el) {
        el.focus();
      }
    }
  }
};
</script>
Enter fullscreen mode Exit fullscreen mode

7. Scoped Styles with CSS Modules

Vue.js supports CSS Modules, which allow you to encapsulate styles within a component. By enabling CSS Modules, you can avoid style conflicts and maintain a modular structure:

<template>
  <div :class="$style.container">
    <p :class="$style.text">Scoped Styles with CSS Modules</p>
  </div>
</template>

<style module>
.container {
  background-color: blue;
}

.text {
  color: white;
}
</style>
Enter fullscreen mode Exit fullscreen mode

Here, the styles defined within the <style module> block are scoped to the component.

8. Vue.nextTick for Synchronous DOM Updates

Vue.js provides the Vue.nextTick method, which allows you to execute code after the next DOM update cycle. This is useful when you need to perform operations that rely on the updated DOM state:

<template>
  <div ref="myDiv">{{ message }}</div>
</template>

<script>
export default {
  data() {
    return {
      message: 'Hello, Vue.js!'
    };
  },
  mounted() {
    this.message = 'Updated Message';
    this.$nextTick(() => {
      console.log(this.$refs.myDiv.textContent); // Outputs 'Updated Message'
    });
  }
};
</script>
Enter fullscreen mode Exit fullscreen mode

9. Emitting Custom Events from Components

In addition to emitting standard events, Vue.js allows components to emit custom events. This can facilitate communication between components:

<template>
  <button @click="notifyParent">Notify Parent</button>
</template>

<script>
export default {
  methods: {
    notifyParent() {
      this.$emit('custom-event', 'Data to be passed to the parent');
    }
  }
};
</script>
Enter fullscreen mode Exit fullscreen mode

The parent component can listen to this custom event using @custom-event="handler".

10. Using v-html for Rendering HTML Content

By default, Vue.js escapes HTML in data bindings to prevent XSS attacks. However, in some cases, you may want to render HTML content dynamically. You can use the v-html directive for this purpose:

<template>
  <div v-html="htmlContent"></div>
</template>

<script>
export default {
  data() {
    return {
      htmlContent: '<p>Rendered HTML content</p>'
    };
  }
};
</script>
Enter fullscreen mode Exit fullscreen mode

Caution: Be careful when using v-html with user-generated or untrusted content to prevent potential security risks.

These 10 Vue.js tricks will enhance your Vue.js development skills and allow you to build more efficient and powerful applications. Keep exploring and leveraging the capabilities of Vue.js to create amazing experiences!

If you like:
Buy me a coffee ☕

Author: Hakimov-dev

Top comments (1)

Collapse
 
michaelsynan profile image
Michael Synan

Love it, this was very helpful. Bookmarked!