I have a Vue 3 App that i want to Call Global Component's Method from Another Component.
Here is the code:
//main.js
import { createApp, h } from 'vue';
import Loading from '@/components/Loading'; // Global Loading Component
const App = {
computed: {
ViewComponent () {
return require(`./views/Index.vue`).default
}
},
render () {
return h(this.ViewComponent)
},
}
const app = createApp(App);
app.component('Loading', Loading); // Adding it to Global
app.mount('#app');
//@/components/Loading.vue
<template>
<div id="darken"></div>
<div id="loading">
<img src="@/assets/images/loading.gif" />
</div>
</template>
<script>
export default {
name: 'Loading',
methods: {
showLoading(){
document.getElementById("darken").style.display = "inline";
document.getElementById("loading").style.display = "inline";
},
hideLoading(){
document.getElementById("darken").style.display = "none";
document.getElementById("loading").style.display = "none";
}
}
}
</script>
<style>
#darken {
position: absolute;
display: none;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: black;
opacity: 0.5;
}
#loading {
position: absolute;
display: none;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%); /* for IE 9 */
-webkit-transform: translate(-50%, -50%); /* for Safari */
}
#loading img {
width: 400px;
}
</style>
//@/views/Index.vue
<template>
<!-- Design Stuff ... -->
<button v-on:click="login()">Login</button>
<loading />
</template>
<script>
export default {
methods: {
login(){
//this.$refs.Loading.showLoading(); // this works when i add ref="Loading" to the <loading /> tag
// but i need something better, something like "this.$components.Loading.showLoading();"
// adding ref="Loading" with the loading tag is not convenient for me // is there alternative?
}
}
}
</script>
I Looked a lot and couldn't find what i am looking for.
Any ideas?, i would really appreciate it. Thank you.
PS: I am new to Vue.js but i am a fast learner.