乐闻世界logo
搜索文章和话题

How to call a custom global function using composition api | vue3

1个答案

1

In Vue 3, calling global functions using the Composition API involves several steps, primarily registering these functions during application initialization and then invoking them appropriately within components where they are needed. Here are the detailed implementation steps:

Step 1: Define Global Functions

First, define your global functions in a separate file. Typically, these utility functions reside in a dedicated file such as utils.js:

javascript
// utils.js export function formatDate(date) { return date.toISOString().slice(0, 10); } export function capitalize(text) { return text.charAt(0).toUpperCase() + text.slice(1); }

Step 2: Register Global Functions in the Vue Application

Next, register these functions when creating the Vue application using global properties (e.g., app.config.globalProperties), ensuring they are accessible across all components.

javascript
// main.js import { createApp } from 'vue'; import App from './App.vue'; import { formatDate, capitalize } from './utils'; const app = createApp(App); // Register functions as global properties app.config.globalProperties.$formatDate = formatDate; app.config.globalProperties.$capitalize = capitalize; app.mount('#app');

Step 3: Use Global Functions in Components

Within components, access the component instance via the Composition API's getCurrentInstance method to utilize these global functions.

vue
<template> <div> <p>Formatted Date: {{ formattedDate }}</p> <p>Capitalized Text: {{ capitalizedText }}</p> </div> </template> <script> import { ref, onMounted, getCurrentInstance } from 'vue'; export default { setup() { const { proxy } = getCurrentInstance(); const formattedDate = ref(''); const capitalizedText = ref(''); onMounted(() => { const today = new Date(); formattedDate.value = proxy.$formatDate(today); capitalizedText.value = proxy.$capitalize('hello'); }); return { formattedDate, capitalizedText }; } } </script>

In this component, access the registered global functions through getCurrentInstance().proxy and invoke them within the onMounted lifecycle hook. Use ref to maintain reactivity and display results in the template.

Summary

By following these steps, you can successfully register and call global functions in Vue 3's Composition API environment. This approach enhances code modularity while preserving function reusability and accessibility. In practical development, this pattern is ideal for handling common tasks like data formatting and computed properties.

2024年11月20日 22:15 回复

你的答案