Utilize Vuex store in Vue without the need for import statements within components

When working with Vue 2/3 and in an ES6 environment, I often access a Vuex store in an external JS file using the following method:

// example.js

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

console.log(store.state.currentUser);

While this method works well, in my current setup (Rails 5 without webpack), I am unable to use import statements.

Question: Is there a way to access Vuex stores outside of components using regular ES5 JavaScript?

I have successfully set up Vuex on our frontend, but we are facing limitations in accessing it outside of defined Vue components.

Answer №1

Within my Rails configuration, I have the following setup:

// 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);

});

Here, the store variable acts as a global javascript object that can be utilized like any other JS object.

Given that you are working within a properly compiled JS file and have correctly installed your base Vue, accessing store.state.activity.activities or executing mutations like

store.commit('myMutation', 'Hello test')
is straightforward.

An example of how I implemented this was within a lengthy function triggering a webhook. The webhook may take some time to process, prompting me to send status updates to the user as new information becomes available.

For instance:

// webhook.js

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide to conditionally adding a property to an object in JavaScript

After scouring both Stack Overflow and Google for a solution, I finally stumbled upon this brilliant idea: x = { y: (conditionY? 5 : undefined), z: (conditionZ? 5 : undefined), w: (conditionW? 5 : undefined), v: (conditionV? 5 : undefined), u ...

Trouble arises when implementing personalized buttons on the Slick JS slider

Are you struggling to customize buttons for your Slick Slider JS? I am facing a similar issue with applying my own button styles to the slider. I am interested in using arrow icons instead of the default buttons. Here is the HTML code snippet: <secti ...

What could be causing document.getElementById to return null?

I've been troubleshooting my code and noticed that one of the methods in my JavaScript file is not functioning correctly. Does anyone have any insights into why this might be happening? index.html: <!DOCTYPE html> <html lang="en"> <he ...

JWPlayer has a built-in delay of 5 seconds before executing an action following the completion of a

I am looking to customize the JWPlayer so that it pauses for 5 seconds before playing the next video. Additionally, I want to display a loading animation at the center of the video similar to what is seen on YouTube. Here is the code snippet I am currently ...

Exploring the possibilities of leveraging Vuex map helpers through the Composition API

Can you assist me in using the Composition API in Vue2 to access mapState? I am looking to monitor state changes and would like to use it within the setup function as well, not just in the return statement. Your help is much appreciated. ...

Creating Angular Modal on ng-click

I'm facing a challenge with a seemingly simple task. Within an ng-repeat, I have a table of events. My goal is to enable users to click on the event name and view detailed information in a modal window. To achieve this, I have set up an ng-click="ev ...

"Exploring the usual progress of a standard GET request using Axios

My Objective: I am utilizing Vue And Axios, with the goal of displaying the progress in percentage on the console. The Challenge: The request itself takes around 4 seconds or more because it fetches a large amount of data, processes it into an excel fil ...

Struggling to get this bootstrap carousel up and running

I can't seem to get this bootstrap carousel to switch slides, whether I use the indicators or arrows. My other carousel works perfectly fine and I've added all necessary Bootstrap and JavaScript CDNs. I'm puzzled as to why it's not func ...

Looking to achieve a mouse over effect in jQuery?

For the past few days, I've been grappling with a question that I just can't seem to find the right answer to. I'm trying to create a mouseover effect similar to the one on this template (the Buddha at the top of the page). Despite my best e ...

Guide to locating and substituting two integer values within a string using JavaScript

Given a string such as: "Total duration: 5 days and 10 hours", where there are always two integers in the order of days and then hours. If I need to update the old string based on calculations using fields and other values, what is the most efficient meth ...

Generating a JSON download link using AngularJS

I'm attempting to generate a link that will enable the download of a JSON file in this way Controller $scope.url = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(obj)); View <a href="url" download="download.json">downlo ...

Tips for displaying autocomplete suggestions as clickable links?

I am new to using Ajax and trying to figure out how to display autocomplete results as clickable links. I have managed to list the related results, but I am struggling to add the links. I believe the links need to be added within the script as an HTML tag. ...

Steps to invoke a function to add an element into a list

Every time a user clicks on a button, I want to generate a new tab. In this tab, when the user clicks again, I want a function to be called like: onclick('+reportname+','+report type+') onclick("'+reportname+'","'+repor ...

Struggling to map a JSON file in a NextJS project using Typescript

I'm a beginner in JS and I'm currently struggling to figure out how to display the data from a json file as HTML elements. Whenever I run my code on the development server, I encounter the error message: "props.books.map is not a function&q ...

Having trouble creating a unit test for exporting to CSV in Angular

Attempting to create a unit test case for the export-to-csv library within an Angular project. Encountering an error where generateCsv is not being called. Despite seeing the code executed in the coverage report, the function is not triggered. Below is the ...

Retrieving a targeted JSON element and adding it to a fresh object

Hello everyone, I have an object that resembles the following structure: [ { "app": 1, "scalable": true, "zoomable": true, "cropBoxResizable": true }, { "app" ...

Is it better to use relative or absolute resource scripts in an AngularJS application?

My project involves building a single-page JavaScript app using AngularJS. In order to achieve this, the index.html file has a specific structure: <html> <head> <base href="/" /> ... </head> <body id="ng-app" ng-app="myAngularAp ...

Exploring the functionality of the instanceof operator in Javascript

I'm currently developing a Node.js application and the project structure is as follows: [Project Folder] | |---[plc] | |--- plc.js | |--- scheduler.js | |---[source] | |--- source.js | |---[test] |--- test.js Th ...

Tips for effectively utilizing npm-check

Recently, I've been delving into the world of node.js and experimenting with the Spotify API to enhance my knowledge. After starting off with some example source code provided by Spotify, I now feel ready to create something unique on my own. With a ...

Typescript Angular filters stop functioning properly post minification

I developed an angular filter using TypeScript that was functioning properly until I decided to minify the source code. Below is the original filter: module App.Test { export interface IGroupingFilter extends ng.IFilterService { (name:"group ...