Adding Global Properties and Custom Directives API
Learn the new way of adding global properties and custom directives in Vue 3.
We'll cover the following...
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:
Press + to interact
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:
Press + to interact
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.
...