Using vuex-class to interact with Vuex in non-Vue components

Is it possible to access Vuex outside of a Vue component using vuex-class?

In a typical scenario, the process is quite straightforward:

// some JS file
import store from './../store'; // path to Vuex store

store.commit('ux/mutationName', somePayload)

However, if you are utilizing vuex-class and have a Vuex module set up like this:

import { Module } from 'vuex';
import { RootState } from '@/types/vuex/types';
import { MutationTree } from 'vuex';
import { GetterTree } from 'vuex';

const namespaced: boolean = true;

export interface UXState {
  compLoading: boolean;
}

export const state: UXState = {
  compLoading: false
};

export const mutations: MutationTree<UXState> = {
  setCompLoading(state, payload: boolean): void {
    state.compLoading = payload;
  }
};

export const getters: GetterTree<UXState, RootState> = {
  compLoading(state): boolean {
    return state.compLoading;
  }
};

export const ux: Module<UXState, RootState> = {
  namespaced,
  state,
  mutations,
  getters
};

To access Mutations from the store outside of a Vue component:

<script lang="ts">
  import axios from 'axios';
  import {Mutation} from "vuex-class";
  const namespace: string = "ux";

  @Mutation('setCompLoading', { namespace })
  const setCompLoading!: (flag: boolean) => void;

  async function fetchData() {
      setCompLoading(true);
      const resp = await axios.get('someURL');
      setCompLoading(false);
  }

  fetchData();
</script>

How can I utilize vuex-class with TypeScript to access Mutations outside of a Vue component?

Answer №1

Despite utilizing vuex-class, you still have the option to employ mutations in the traditional manner:

import store from './../store';

store.commit('module/mutationName', payload);

Alternatively, if you favor utilizing typed mutations directly:

import state from './../store/state';
import { MUTATION_NAME } from  './../store/mutations'; // Or wherever they're located

MUTATION_NAME(state, payload);

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

Angular Error: Unable to access the 'title' property of an undefined value

Error Message Showing on Console for post-create.component.html ERROR Message: TypeError: Cannot read property 'title' of undefined at PostCreateComponent_Template (template.html:13) I suspect the issue is related to this line - console.log(for ...

Selecting a event from Google Places Autocomplete using a mouse click

I have successfully implemented Google's autocomplete API as per the documentation. However, I am facing an issue with a form that is submitted via Ajax every time it changes. The problem arises when using the autocomplete feature for location selecti ...

Angular 9 Issue: Failure to Display Nested Mat-Tree Children

Hello everyone, I'm new to posting questions on Stack Overflow and I'm seeking some assistance with an issue I'm having with Mat-Tree. Despite the fact that my data is present when I console log it, the children are not appearing. I am fetc ...

Unable to link to 'Attribute A' because it is not recognized as a valid property of 'Subcomponent'

Within my project, I have a generic class with several components that inherit from it. BaseRdnInput.ts: @Injectable() export abstract class BaseRdnInput implements ControlValueAccessor, Validator { @Input() rdnModel?: any | Array<any ...

Sketch a variety of numerical values in a circular formation

I was working on a number circle using the below fiddle, but I need it to always start from 0 at the top. How can I achieve this? Additionally, I would like to connect the numbers from the inner circle border to the number with a dotted line. How can I dr ...

Tips for transferring the value of a text box between components bidirectionally in Angular 8

Let's create a scenario where we have two components: login and home. The goal is to capture the value entered in the text box of the login component and pass it to the text box in the home component when the "proceed" button in the login component is ...

Attempting to create a redirection landing page

I have a process where I create a new user and save it in my database with the following code snippet: const newUser = new User({ username: userId, password: pass, nameOfUser: user_name, emailOfUser: user_email ); newUser.save(); res.redir ...

what's causing the tabs in bootstrap to malfunction

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> <link href="http://maxcdn.bootstrapcdn.com/bootst ...

React: Modifying state does not update useState array

The state of the array does not change when the state change method is called : const [arrayOfDocuments, setArrayOfDocuments] = useState([]); I have tried : setArrayOfDocuments(...[]); or setArrayOfDocuments([]); Where I use my method : const pushToArr ...

Socket.io operates individually with each user

Showing a basic web-chat using socket.io. Node.js code: io.on('connection', function(socket) { // Sends 'hello world' message to all users socket.emit('send:message', { text: 'hello world' }); ...

What is the process for choosing a table column by clicking on the "select" option?

Welcome to my project! Here is an example table that I'm working on. I have a question - how can I make it so that when I click on "choose me", the entire column is selected? Can you help me with this? <table> <tr> <th>plan A&l ...

AngularJS ng-switch-trigger enclosed within its own ng-switch-wrapper

In my current project, I am working on switching between two buttons that act as their own triggers for the switch. To illustrate further: <span ng-switch on="patientSwitch"> <span ng-switch-when="edit"> <button ng-click="patien ...

Error: Unable to generate MD5 hash for the file located at 'C:....gradle-bintray-plugin-1.7.3.jar' in Ionic framework

When attempting to use the command ionic cordova run android, an error occurred that prevented the successful execution: The process failed due to inability to create an MD5 hash for a specific file in the specified directory. This issue arose despite suc ...

TypeScript's attempt to replicate Scala's underscore feature has been implemented, but it proves to

I've been working on a personal project for the past 2 years trying to implement Scala's underscore in TypeScript, but haven't been successful. Here is my attempted implementation and its effect. The only thing that I really care about typi ...

Memory Match: Picture Edition

In this memory game, letters are used. I had considered changing it to a picture-based game, but I faced difficulty in generating images and incorporating them into the array. <script> var memory_array = ['A', 'A', 'B&ap ...

Connecting data to a file input's value: A guide on binding in HTML

I have successfully retrieved data for objects from an API and now need to display it in an input field so I can edit it later. I have managed to achieve this with text values using v-model. However, I am unsure of how to display the file name that is be ...

What is the best way to include a new user in my list of friends within the User schema?

Working on my customized social media platform, I have implemented a feature where users can send friend requests by clicking on a button. <form action="/requests" method="POST"> <input type="hidden" name="send ...

How can one properly utilize material-ui CSS?

Just starting out with material-ui and react, I'm currently following this palette customization guide from Material-UI. However, when attempting to replicate the example shown, I encountered the error: Cannot read property 'prepareStyles' ...

Utilizing Angular to intercept AJAX requests, verifying internet connectivity before proceeding with sending the request

In my Angular (with Ionic) app, I have this code snippet: my_app.factory('connectivityInterceptorService', ['$q', '$rootScope', function ($q, $rootScope) { var connectivityInterceptorServiceFactory = {}; var _request ...

Interacting with react-virtualized: accessing Grid's public functions

Trying to utilize the public method recomputeGridSize on a Grid component that I am currently rendering. I have set up the ref, but when attempting to call the method, it seems like it is not accessible. Outlined below is where the ref is established with ...