Utilize `mapActions` or `mapGetters` in conjunction with Vuex 4 and Vue 3

Is there a way to utilize mapState or mapGetters in Vue 3's setup function? I am aware that the useStore hook can be used to interact with the store, but it imports the entire store. On the other hand, using mapState or mapGetters allows us to specify a specific module:

// ...

computed: {
   ...mapGetters('myModule', [
      'myStateVariable'
   ]
) 

//...

Answer №1

Here is a potential solution:

import { computed }  from 'vue';
import { useStore } from 'vuex';

const moduleName = 'myModule';

export default {
    setup() {
        const store = useStore();

        return {
            // getter
            one: computed(() => store.getters[`${moduleName}/myStateVariable`],

            // state
            two: computed(() => store.state[moduleName].myStateVariable,
        };
    },
};

Answer №2

It appears that the variables are compressed, making it impossible to access using myModule/myStateVariable, but simply myStateVariable should still work.

As Vuex moves towards RC releases, this behavior may change in the future. Currently, attempting to use the same getter twice will result in an error like the one shown below:

https://i.sstatic.net/tEetj.png

Answer №3

Using Vue 3 and Vuex 4, I was able to achieve this setup: Let's assume we have a store structured like this:

https://i.sstatic.net/qBtrg.png

Our main store index.js (at the bottom) would look something like this:

 import { createStore, createLogger } from 'vuex';
 import module1 from '@/store/module1';
 import module2 from '@/store/module2';


 export default createStore({

 modules: {
    module1: module1,
    module2: module2,
 },
 plugins: process.env.NODE_ENV !== 'production'
 ? [createLogger()]
 : []
})

Each module would then have an index.js file like this:

import * as getters from './getters'
import * as actions from './actions'
import mutations from './mutations'


const state = {
  postId: 10111,
}

export default {
  namespaced: true,

  state,
  getters,
  actions,
  mutations,
  
}

The getter function in each module would be defined as follows:

export const getPostId = state => {
   return state.postId 
}

In a component, you can access the getters like this:

<template>
 <div>
   <div class="major_container">
     <p>{{ postIdFromModule1 }}</p>
     <p>{{ postIdFromModule2 }}</p>
  </div>
</div>
</template>
<script> 
import { computed } from "vue";
import { useStore } from "vuex";

export default {
 setup() {
   const store = useStore();

   const postIdFromModule1 = computed(() => store.getters["module1/getPostId"]);
   const postIdFromModule2 = computed(() => store.getters["module2/getPostId"]);

   return {
     postIdFromModule1,
     postIdFromModule2,
   };
  },
};
</script>

Now, your modules are properly namespaced and ready for use!

Answer №4

If you want to effectively utilize the mapActions method in a Vue3 style Single File Component, the recommended approach is to include it within the setup() function's return statement.

import { mapActions } from "vuex"
setup() {
  return {
    ...mapActions("myModule", ["doSomething"])
  }
}

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

Angular2 - Implementing Form Validation for Dynamically Generated Input Fields Based on Conditions

My goal is to create a basic form that allows users to select between two options: Local and Foreigner. If the user does not make a selection, the form should be marked as invalid. Choosing Local will make the form valid, while selecting Foreigner will rev ...

What is the best way to extract just the hours and minutes from a timestamp column that includes hours, minutes, and seconds in my dataset and create a new column

Is there a way to extract only the hour and minute values from a timestamp column that includes seconds in my dataset? ...

Using custom directives in Vue 3 does not allow passing data to a method

Within my HTML, I make a reference to the directive: v-init:url="myurlhere" data() { return { currentPage: 1, url: '', news: '', } }, directives: { init: { mo ...

The background color of the Bootstrap 5 navbar remains static and does not transition when scrolling

I'm currently developing an Angular application using Bootstrap 5. One of the features I am working on is a transparent navbar that should change to a dark color when the page is scrolled. However, I seem to be encountering an issue where the navbar r ...

How to Create a DataTable Responsive Feature Where All Columns Collapse on Click, Except the Last One?

I am currently utilizing the DataTables library to generate a responsive table. I am aiming to create a feature where all columns in the DataTable can toggle between collapse and expand states when clicked, with the exception of the last column. Below is a ...

How can we use Mongoose .find to search with an array stored in req.params and respond with an array containing each value along with its

It would be great if a user could input multiple tags in a search field, and have them separated client-side (before making the .get call) to send over ajax with each keypress. While testing the API with Postman on the server-side, if the .get method retu ...

Javascript code requires server to have default text field values

Based on the choice made by a user, a text field box will either remain concealed or revealed: $("#aForm").on("change", function() { if ($(this).val() == "a") $("#textField").hide(); else $("#textField").show(); }); The issue arises when the ...

Error Message: The function "menu" is not a valid function

I've encountered an issue with a function not being called properly. The error message states "TypeError: menu is not a function." I attempted to troubleshoot by moving the function before the HTML that calls it, but unfortunately, this did not resolv ...

What is the best way to bring in an SVG file to be able to access its attributes?

Currently, I am working with a large SVG and my goal is to access its 'path' to make modifications. Originally, I inserted the SVG directly into my application, but now I want to organize my code better by moving the SVG into its own file. This w ...

Page reloads are disabled when Chrome devtools debugger is paused in a React app

Currently, I am in the process of troubleshooting a React application that was created using create-react-app. Whenever I attempt to reload the page while paused on a breakpoint, it results in the page stalling. The screen goes blank and is unresponsive t ...

A guide on navigating to a different component in Vuejs using a link

<div class="enterprise-details" style="margin-top: 20px"> Already signed up? <a href="#"> LOGIN</a></div> <!-- Component for redirection --> <b-button v-if="!registeredUser" class="button-self" v-b-modal.modal-x>Lo ...

`How can the background color be altered based on specific conditions?`

I am attempting to modify the background color. My goal is to change every odd result to a light green (#f0f5f5) to avoid a large white space when the result ends in an even number. I would also like to change the background color of the pagination section ...

Retrieve the HTML code for every class name

What is the best way to extract all the HTML content from a specific class that is used multiple times? $(document).ready(function(){ $("span.feeditemtext.cxfeeditemtext").each(function() { alert($(this).html()); }); }); ...

What is the most efficient way to loop through an array and send each item to a method, ensuring that all methods are executed synchronously?

I need to make a request method call that retrieves its own body as an array, which is one item within another array. To achieve this, I have to iterate over the parent array and pass each of its items to the request method for a new server request. I tr ...

Is there a way to set the jQuery MultiSelect widget to be read-only mode?

Is there a way to set Eric Hynds' MultiSelect plugin for jQuery UI to read-only mode? I already know how to disable the widget, but I'm looking to show its contents without allowing any user interactions. ...

Learn how to extract values from an object in Vue JS time-slots-generator and display either PM or AM based on the

Using the time-slots-generator package, I am able to display the time from 0:15 to 24:00. However, the issue is that this package does not have built-in functionality to display AM/PM, so I had to create a manual solution for it. To achieve this, I modifi ...

Tooltip's onclick event not triggering

Take a look at this link: If you click on the jacket, you will see an alert pop up saying "here". By examining the page source, you'll find the onclick event responsible for triggering this alert. Hovering over the jacket will reveal a tooltip. I em ...

Creating individual product pages from an array of objects: A step-by-step guide

Is there a way in Next.js to create individual pages for each object in an array with unique URLs? Here is the input array: Input Array const products = [ { url: "item-1", id: 1, name: "Item 1", description: "lor ...

Having trouble with SQLite and local storage in Android PhoneGap app specifically on Samsung Galaxy devices

My PhoneGap app is running smoothly on iOS and most Android devices, but I'm encountering an issue specifically with Samsung Galaxy S3 and S4. Upon the initial page load, the app creates a local SQL database to store question and answer values. Howev ...

Understanding the Relationship Between Interfaces and Classes in Typescript

I’ve come across an interesting issue while working on a TypeScript project (version 2.9.2) involving unexpected polymorphic behavior. In languages like Java and C#, both classes and interfaces contribute to defining polymorphic behaviors. For example, i ...