Top 10 Vue.js Tricks You Might Not Know
Tags: javascript, vue, nuxt, webdev
Published: 2023-06-15 10:00:23

## 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>
```

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


## 2. Conditional Components with <component> 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>
```

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>
```

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

4. 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>
```

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>
```

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>
```

## 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>
```

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>
```

## 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>
```
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>
```

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 ☕](https://www.buymeacoffee.com/hakimovDev)


> Author: [Hakimov-dev](https://hakimov.netlify.com)