Search code examples
javascriptvue.jsvuexecmascript-5

Vue: Use Vuex store outside of component without Import Statements


In Vue 2/3, and in an ES6 environment when I want to access a Vuex store in an external JS file (outside of the component), I would normally use something like this:

// example.js

import { store } from '../store/index';

console.log(store.state.currentUser);

This works great, however, in my current environment (Rails 5 without webpack), we can't use import statements at all.

Question: Is there any way, in regular ES5 JavaScript, to access Vuex stores outside of components?

It's worth noting that I've got a successful setup of Vuex going on our frontend, we just can't access it outside of our defined Vue components.


Solution

  • In my Rails setup, I have this:

    // app/assets/javascripts/lib/vuex/store.js
    
    const store = new Vuex.Store({
      modules: {
        activity: activityStore,
      }
    });
    
    // application.js
    
    //= require vue/dist/vue.min
    //= require vuex/dist/vuex.min.js
    
    $(document).ready(function () {
    
      Vue.use(Vuex);
    
    });
    

    In this instance, store is just a global javascript object. Use it the same as you would any other JS object.

    As long as you're inside a JS file that is properly compiled, and your base Vue is installed properly, you can just do store.state.activity.activities, or if you have mutations, store.commit('myMutation', 'Hello test').

    My specific example was a huge function calling a webhook. The webhook can take a while, and I want to send messages to the user as I get new messages.

    Example:

    // webhook.js
    
    async webhookFunction() {
      // new message recieved
      store.commit('newActivity', 'Your object has been updated');
    }