Vue.js Global Object

Oct 29, 2019

Declare global object

const app = Object.freeze({  name: 'My App',  version: '1.0.1',  GOOGLE_API_KEY: '...',  items: [    {id: 1, name: 'Desmond'},    {id: 2, name: 'Meiru'}  ],  findItem(id) {      return this.items.find(item => item.id === id)  }})Vue.prototype.$app = app

Access global object in component

<template>  <div>    {{ $app.name }} ({{ appNameUpper }})    {{ item.name }}  </div></template><script>export default {  computed: {    appNameUpper() {      return this.$app.name.toUpperCase()    },    item() {      return this.$app.findItem(1)    }  }}</script>

NOTE: Adding Instance Properties

Other options

  • Global Mixin
  • Webpack Global: global.$app = app, after which you can access $app.name from anywhere.

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.