tezvyn:

Vue Plugins: Add App-Wide Functionality

AI-drafted, machine-checkedSource: vuejs.orgadvanced

A Vue plugin packages reusable logic to add features across your entire app, like a global toolbox. Use them for routing, state management, or making custom functions globally available.

WHY IT EXISTS Plugins exist to solve the problem of sharing functionality—like components, methods, or configuration—across an entire application without manually importing it everywhere. They provide a clean, centralized way to install and extend Vue's core capabilities on an app-wide level.

THE MENTAL MODEL A plugin is like an add-on for your Vue application. You install it once with app.use(), and it injects new features, components, or methods that become available globally. It's the standard way to integrate larger libraries like vue-router or to share your own custom utilities throughout your project.

HOW IT WORKS A plugin is an object with an install method, or simply a function that acts as the install method. This method receives the Vue application instance (app) and any options you pass. Inside install, you can extend the app in several ways: register global components with app.component(), add global methods with app.config.globalProperties, or provide resources to all child components with app.provide().

WHEN TO USE IT Use plugins when you need to provide functionality across many components. Common use cases include: first, adding a routing system (like vue-router); second, implementing a global state management solution (like Pinia); third, creating a set of shared utility functions, like a translation helper or an HTTP client instance that needs to be available everywhere.

WHEN NOT TO USE IT Avoid plugins for logic that is only needed within a small, specific part of your application. For component-specific logic, use local state or props. For reusable logic shared between just a few components, prefer Composables, which are more explicit and don't pollute the global scope.

ONE CANONICAL EXAMPLE A simple internationalization (i18n) plugin. You define an object with an install(app, options) method. Inside, you attach a $translate function to app.config.globalProperties. This function takes a key (e.g., 'greetings.hello') and uses the options object passed during installation (app.use(myPlugin, { greetings: { hello: 'Bonjour!' } })) to find and return the translated string. Now, {{ $translate('greetings.hello') }} works in any component template.

Read the original → vuejs.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.