An open API service indexing awesome lists of open source software.

https://github.com/mini-ghost/vue-async-mount-component

A Vue utility for lazy-loading components and keeping them mounted even when closed.
https://github.com/mini-ghost/vue-async-mount-component

Last synced: 8 months ago
JSON representation

A Vue utility for lazy-loading components and keeping them mounted even when closed.

Awesome Lists containing this project

README

          

# Vue Async Mount Component

## Installation

```bash
npm install vue-async-mount-component
```

## Usage

```vue

import { defineAsyncMountComponent } from 'vue-async-mount-component'

const LazyModal = defineAsyncMountComponent(() => import('./LazyModal.vue'))

const isActive = ref(false)

```

## Use Cases

In most situations, the `` component is not needed immediately when the page loads. Instead, it is usually required when a user clicks a button or triggers an event. Therefore, we want to avoid loading the component until it is actually opened for the first time. Additionally, once the component is loaded, we want to keep it in the mounted state even when it is closed, so it does not need to be mounted the next time it is opened.

Here is how we can achieve this:

```vue

import { defineAsyncComponent, ref } from 'vue'

const LazyModal = defineAsyncComponent(() => import('@/components/Modal.vue'));

const isActive = ref(false)
let isModalMounted = false



```

In this example, the `` component loads only when it is opened for the first time and stays in the mounted state when closed.

However, if we have to do this every time, it can be cumbersome. We need an extra state to track whether the component has been loaded, and if we have many such components, the code can become messy. `defineAsyncMountComponent` allows us to achieve the same effect more easily.

The approach is almost the same as `defineAsyncComponent`.

```vue

import { ref } from 'vue'
import { defineLazyShowComponent } from '@utils/defineLazyShowComponent'

const LazyModal = defineLazyShowComponent(() => import('@/components/Modal.vue'));

const isActive = ref(false)

```