Here are the steps you need to follow:
- Assign your Vue app to a variable that is available globally.
- Once you have made it globally available, call a method defined as
methodName
in its method
s directly (e.g: myVar.methodName()
, not as myVar.methods.methodName()
!!!)
How to make the variable globally accessible:
The traditional way to declare globally available variables is by using the window
object:
window.myVueApp = Vue.createApp(vueApp).mount("#app");
// Access from anywhere else in the window:
window.myVueApp.openModal();
A more contemporary approach to making a variable globally accessible is through window
's alias: globalThis
:
globalThis.myVueApp = Vue.createApp(vueApp).mount('#app');
// Both of these will now work
// Because, inside a browser, globalThis === window
window.myVueApp.openModal();
globalThis.myVueApp.openModal();
Note: Can I use globalThis?
Even though window
has an alias in globalThis
, using it is still not recommended due to potential issues (explained below).
Note: Introducing variables into the global scope is generally considered as bad practice, as it increases the risk of name conflicts (when multiple scripts unintentionally use the same global scope variable names).
In theory, this can lead to unreliable code that may fail under certain conditions. It's best to write robust code that does not disrupt other scripts running on the same page.
To reduce the risk of naming collisions, you can encapsulate your app within the Vue
namespace, which already exists globally and is unlikely to be used by others:
Vue.myVueApp = // ...your app here...
Check out this example:
const vueApp = {
data() {
return {
showContent: false,
}
},
methods: {
openModal: function() {
this.showContent = true
},
closeModal: function() {
this.showContent = false
}
},
};
Vue.myModeratelyAmazingVueApp = Vue.createApp(vueApp).mount("#app");
<script src="https://unpkg.com/vue@next/dist/vue.global.prod.js"></script>
<div id="app">
<button @click="openModal">Click</button>
<div id="dbg_overlay" v-show="showContent" @click="closeModal">
<div id="content"></div>
<button @click="closeModal">Close</button>
</div>
</div>
<button onclick="Vue.myModeratelyAmazingVueApp.openModal()">external open</button>