Search⌘ K
AI Features

Adding Global Properties and Custom Directives API

Explore how to add global properties in Vue 3 and adapt custom directives following new lifecycle methods. Understand the differences from Vue 2 and prepare your migrated app for optimal functionality.

Adding global properties

Let’s look at how we deal with global properties in Vue 2 and Vue 3.

Vue 2 and Vue 3

In Vue 2, we could add a new property on Vue’s prototype to make a value available in all components. For instance, we could add a global debug method by doing this:

JavaScript (JSX)
Vue.prototype.$debug = msg => console.log(`Debug: ${msg}`)

However, this doesn’t work in Vue 3, as a Vue application instance is created with the createApp method that returns an isolated Vue context. There’s now a different way of adding global properties:

JavaScript (JSX)
const app = createApp({})
app.config.globalProperties.$debug = msg => console.log(`Debug: ${msg}`)

There’s an example of adding global properties for Vue 2 and Vue 3 at the end of the previous lesson and in which the getRandomNum method worked as global properties.

Custom directives API

The ...