SoFunction
Updated on 2025-04-11

Seven advanced usages in in-depth exploration

1. Create multiplexing logic using the Composition API

The Composition API is an important feature introduced in , which allows developers to organize the logic of components in a more flexible way. passsetupFunctions, we can define the responsive states, computed properties, and methods of components, and then return them to the template for use. More importantly, the Composition API makes logical reuse simple and clear. By customizing the combination function, we can encapsulate component logic and share it among multiple components. This approach not only reduces code duplication, but also makes the maintenance and testing of components easier.

import { ref, onMounted } from 'vue';

export function useFetchData(url) {
  const data = ref(null);
  const error = ref(null);

  onMounted(async () => {
    try {
      const response = await fetch(url);
       = await ();
    } catch (e) {
       = e;
    }
  });

  return { data, error };
}

2. Teleport - Flexible use of modal boxes

In,TeleportProvides the ability to render child components to anywhere in the DOM tree, which is especially useful for modal boxes, notifications, etc. UI elements that need to be separated from conventional streams. useTeleport, we can define the content of the modal box inside the component, and then passtoThe property specifies the target position to which the modal box should be rendered, such asbody. This way, even if the modal box is nested deeply in the component hierarchy, it ensures that it is rendered in the right place on the page, avoiding CSS style conflicts and hierarchy issues.

<template>
  <Teleport to="body">
    <div v-if="isModalOpen" class="modal">This is a modal box</div>
  </Teleport>
</template>

<script setup>
import { ref } from 'vue';

const isModalOpen = ref(false);
</script>

3. Use Suspense to handle asynchronous components

SuspenseIt is a new component that is specifically used to handle the loading state of asynchronous components. In the past, we needed to handle load states and error states inside components, and the code often became complicated. And there isSuspense, we just need to put the asynchronous component in its default slot and passfallbackSlot definitions fallback content during loading.SuspenseAutomatically detects parsing process of asynchronous dependencies, gracefully handles loading state, and simplifies the use of asynchronous components.

<Suspense>
  <template #default>
    <AsyncComponent />
  </template>
  <template #fallback>
    <div>Loading...</div>
  </template>
</Suspense>

4. Structural assignment of responsive Refs

The responsive system allows us to use it directly through structure assignmentrefDefine responsive data while maintaining its responsiveness. This is especially useful when using the Composition API, because we often need to extract values ​​from responsive objects. In this case, these values ​​are still responsive even after being assigned through structures, which makes state management more flexible and intuitive.

import { ref, onMounted } from 'vue';

const state = ref({ count: 0 });

onMounted(() =&gt; {
  const { count } = toRefs();
  (); // Stay responsive});

5. Use provide/inject to implement cross-component communication

provideandinjectThe API provides an elegant solution for cross-component communication in Vue applications. Through this pair of APIs, ancestor components can define data or methods that can be provided to all of their descendants, and descendants can useinjectto receive these data or methods without passing them layer by layer through each layer of components. This is particularly important for the development of deeply nested components and higher-order components, greatly improving the maintainability and readability of the code.

// Parent componentimport { provide } from 'vue';

export default {
  setup() {
    provide('message', 'Message from the parent component');
  }
}

// Subcomponentsimport { inject } from 'vue';

export default {
  setup() {
    const message = inject('message');
    return { message };
  }
}

6. Use of custom directives

The custom directive API in the custom directives API has also been improved, making creating and using custom directives more flexible and powerful. Custom instructions allow us to encapsulate reusable DOM operation logic, such as focus management, drag-and-drop interaction, etc. In this, the life cycle hook of custom instructions is expanded, and we can control the mount, update and uninstall behavior of instructions more carefully, providing more possibilities for developing complex interactions.

import { createApp, directive } from 'vue';

const app = createApp({});

('focus', {
  mounted(el) {
    ();
  }
});

7. Use watchEffect for side effects tracking

watchEffectis a new API that automatically tracks responsive dependencies and performs side effects. andwatchCompared with API,watchEffectThere is no need to explicitly declare the listening data source, it automatically collects all responsive states involved in the side effect function. This makes the code more concise when it is necessary to perform operations based on multiple data changes.watchEffectAutomatic dependency tracking also greatly reduces potential omissions or errors in side effects execution, making the connection between state changes and side effects more closely and reliable.

import { ref, watchEffect } from 'vue';

const count = ref(0);

watchEffect(() => ());

in conclusion

By introducing powerful new features and improvements such as Composition API, Teleport, Suspense, etc., it provides developers with more tools and possibilities to build efficient and responsive web applications. The seven advanced usages introduced in this article are just the tip of the iceberg of rich features. Understanding these advanced usages will help front-end developers make full use of their powerful capabilities and improve development efficiency and application performance.

The above is the detailed content of the seven advanced usages in the in-depth exploration. For more information about advanced usage, please pay attention to my other related articles!