I have a javascript variable which I want to pass globally to Vue components upon instantiation thus either each registered component has it as a property or it can be accessed globally.
Note:: I need to set this global variable for vuejs as a READ ONLY property
How to add a global variable using Vue 3 and vue-cli (or Vite) Note: You can drop the dollar sign from your $globalVariable and just use globalVariable , just like in the documentation. And that's it.
import Vue from "vue";import PopupWindow from "./components/PopupWindow";import App from "./App. vue";Vue. component("PopupWindow", PopupWindow); // global registration - can be used anywherenew Vue({ render: (h) => h(App),}). $mount("#app");
To add it to our plugin, we can go to MyFirstPlugin. js and add it like this inside of our install method. import MyHeader from "./components/MyHeader. vue";export default { install: (app, options) => { /* declare global component */ app.
Just Adding Instance Properties
For example, all components can access a global appName
, you just write one line code:
Vue.prototype.$appName = 'My App'
$
isn't magic, it's a convention Vue uses for properties that are available to all instances.
Alternatively, you can write a plugin that includes all global methods or properties.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With