[Vuejs]-Globally Accessible Component Instance

0👍

This is roughly how I’d do it…

I’d use Composition API, because it makes passing around internals easy

(I’m using popup instead of toast for simplicity)

myPopup.vue


// internal
const popupMessage = Vue.ref('');
const popupVisible = Vue.ref(true);

// external
export const popUpShow = function(message) {
    popupMessage.value = message
  popupVisible.value = true
}
export const popupHide = function () {
    popupVisible.value = false
}

export default {
    setup(){
        return {
        popupMessage, popupVisible, popupHide
    }   
  }
}

Some component, anywhere, composition or class based…

import { popUpShow } from "./myPopup";

export default {
  methods: {
    myTriggeredEvent() {
      popUpShow("I am your Liter")
    }
  }
}

By exposing popUpShow, which acts as a singleton, you can import that from anywhere, and not have to worry about context.

There the drawback in using this kind of setup/architecture is that it doesn’t scale well. The problem happens if your architecture reaches a certain size, and you have multiple triggers coming from various sources that the component needs to have complex logic to handle its state (not likely for this example though). In that case, a managed global store, ie. Vuex, might be a better choice.

Leave a comment