How to register and use global properties in VueJS 3

Tutorials / Web Development

5 minutes
Fri Dec 03 2021
IPOCS

The following article will explain how to register and use global properties in VueJS 3 components or templates. This is essentially what was Vue.prototype in VueJS 2. It's useful when a web developer wants to add a global property that can be accessed in any component instance within the web application.

For example, you want to have global filters to strip any html from a string, or to show an excerpt of an article or maybe convert a snake based string to human readable one.

Setup environment

As usual, we will be using VueJS 3 with the composition API + Vite for the frontend tooling, so you need to have at least NodeJS version 12 to be able to run Vite.

Scaffolding and starting your Vite/VueJs project

There are many ways of scaffolding your new project. We will be using npm in this tutorial:

$ cd ~/Code/
$ npm init vite@latest

You will be prompted to setup your new project, we've chosen the following:

$ npm init vite@latest
✔ Project name: … ipocs-global-properties-example
✔ Select a framework: › vue
✔ Select a variant: › vue

Once the project is created, use the following commands to install the dependencies and start the project in development mode:

$ cd ipocs-global-properties-example
$ npm install
$ npm run dev

Register and implement the global properties

Global properties are registered to the app VueJS instance. That being said, open your main.js file and register your custom global filters that you'd like to be available in all of your components, for example:

import { createApp } from 'vue'
import App from './App.vue'

const myApp = createApp(App)

/**
* REGISTER GLOBAL FILTERS
*/
myApp.config.globalProperties.$filters = {
    striphtml (value) {
        const div = document.createElement('div')
        div.innerHTML = value
        return div.textContent || div.innerText || ""
    },

    limitTo (value, size) {
        if (!value || !size) return ''
        return value.substring(0, size) + "..."
    },

    snakeToHuman (value) {
        if (!value) return ''
        return value.replace(/_/g, ' ')
    }
}

myApp.mount('#app')

Using the global filters in VueJS 3 templates

You can directly use your global filters via the $filters variable in your templates. For example, to strip the html from a string and show an excerpt of 100 charaters, you would do:

<div>{{ $filters.limitTo($filters.striphtml(myContent), 100) }}</div>

Using the global properties via composable method

Once you have registered your global filters you can use them in your components via the getCurrentInstance which provides access to an internal component instance.

To simplify the usage, let's create a new composable called useFilters in src/composables directory

import { getCurrentInstance } from 'vue'

export function useFilters () {
    const vm = getCurrentInstance()
    return vm.appContext.config.globalProperties.$filters
}

and then import it wherever you like to have access to your global filters, for example, edit your src/App.vue and do something like this:

<script setup>
import { computed } from 'vue'
import { useFilters } from './composables/useFilters'
import HelloWorld from './components/HelloWorld.vue'

const filters = useFilters()
const myLongString = 'Lorem ipsum dolor sit amet consectetur adipisicing elit. Similique exercitationem consequuntur excepturi. Accusantium suscipit fugit, cupiditate expedita sit asperiores enim dolore? Amet tenetur culpa, aspernatur ut est ipsam deleniti alias.'
const myExcerpt = computed(() => filters.limitTo(myLongString, 50))
</script>

<template>
    <img alt="Vue logo" src="./assets/logo.png" />
    <HelloWorld msg="Hello Vue 3 + Vite" />
    <div>Excerpt using global filters:</div>
    <pre>{{ myExcerpt }}</pre>
</template>

<style>
#app {
    font-family: Avenir, Helvetica, Arial, sans-serif;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    text-align: center;
    color: #2c3e50;
    margin-top: 60px;
}
</style>

Project sources

The source files used in this article are available on GitHub.

Final words

Are you looking for a custom software development or IT support services? Well, look no further, we provide top-quality software developement and system administration services that will exceed even your most demanding needs. Just submit your request and we'll get back to you shortly.