vuejs2vue-componentvuexquasar-framework

where to store global object in quasar framework


I'm re-writing my old app using Quasar Framework which is based on Vue, and I have a piece of code (class) which encapsulates websocket functionality.

It is a fairly simple concept: user travels from page to page in the app, but if he receives a message he can see a toast message/reply or a counter of unread messages increments.

I'm a little bit lost in the Quasar (Vue) architecture and here is my question:

Where would I store a global object which communicates with outside world, exists as long as the application exists and accessible from anywhere?

I read documentation of Quasar (Vue) but I still don't know where to put it. Vuex doesn't look right since it is not a state of the app. It is more like a faceless component.

Does it mean that I should use a plugin or Vue.prototype or a global mixin or something else?

I appreciate if someone can share their experience and a piece of code describing how to initialize and access this object's methods.


Solution

  • in my opinion:

    Method 1. Use quasar plugin base on Vue prototype (sure you knew it):

    plugins/foo.js

    const fooModule = {
      a: 1,
      doTest() { console.log('doTest') }
    };
    export default ({Vue}) => {
      Vue.prototype.$foo = fooModule;
    }
    

    quasar.conf.js

    plugins: [
      'i18n',
      'axios',
      'foo',
    ],
    

    component bar.vue:

    methods: {
       test () { this.$foo.doTest() }
    }
    

    Method 2. Just use js module

    Because js module is singleton. Wherever you import a js module, it all points to the same pointer.

    So just have GlobalTest.js:

    export default {
      a: 1,
      inc() { this.a = this.a + 1 }
    }
    

    And test1.js:

    import GlobalTest from '/path/to/GlobalTest'
    console.log(GlobalTest.a); // output 1
    console.log(GlobalTest.inc()); // inc
    

    And test2.js:

    import GlobalTest from '/path/to/GlobalTest'
    console.log(GlobalTest.a); // Assuming this was called after test1.js: output 2
    

    I used quasar cli but I just consider quasar as a UI lib.

    --- Updated ---

    It is a fairly simple concept: user travels from page to page in the app, but if he receives a message he can see a toast message/reply or a counter of unread messages increments.

    Depend on the requirements, If you need "reactive" you should use Vuex (best built-in reactive lib) + split the app state into modules, but I only use Vuex when I need "reactive" and avoid it when I just need to read & write the value.