Tips on sending arguments to functions associated with ...mapActions...()?

After analyzing the passage below

export default {
  methods: {
    ...mapActions(["updateData", "resetData"]);
  }
}

I wanted to include a parameter in the called functions. Unsure of the proper way to do this while still using the ...mapAction() call, I ended up modifying it to the following.

export default {
  methods: {
    // ...mapActions(["updateData", "resetData"])
    updateData: function() { this.$store.dispatch("updateData", "names") },
    resetData: function() { this.$store.dispatch("resetData"); }
  }
}

Is this the only solution?

Answer №1

To pass a parameter to a method, simply include it when calling the method. Only one parameter can be sent, which will then be accessible in the actions. No special actions are required when using mapActions.

For instance, you can call the method like this:

<button @click=updateData({data1: 1, data2: 2})>

And in the Vuex store:

const actions = {
  updateData: (state, data) => {
     //The passed parameter 'data' will be available here
  },

And you can still utilize mapActions:

export default {
  methods: {
    ...mapActions(["updateData", "resetData"]);
  }
}

Check out the working fiddle here: you can see the passed parameter in the alert :)


Below is the code implementation of mapActions from the Vuex repository:

export function mapActions (actions) {
  const res = {}
  normalizeMap(actions).forEach(({ key, val }) => {
    res[key] = function mappedAction (...args) {
      return this.$store.dispatch.apply(this.$store, [val].concat(args))
    }
  })
  return res
}

It takes the passed args and includes them as a second argument of the dispatch function.

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

Troubleshooting JavaScript If-Else Statements

Having a bit of trouble with my if else structure. When I enter the correct star name like "Vega", it incorrectly shows me "Error" instead of the expected result "Lyra". Here's my code snippet: var stars = ["Polaris", "Aldebaran", "Deneb", ...

Displaying JSON data from the API on a webpage within a NodeJS weather application

Currently, I am in the process of developing a weather application using NodeJS. I have successfully retrieved JSON formatted data from the weather site's API. Nonetheless, I am perplexed about how to transmit this data to the application. Below is a ...

Ways to display an error notification alongside another message

I have set up a validation directive that requires users to check a box. If the checkbox is left unchecked, an error message will be displayed. However, I am facing an issue where the message overlaps with the checkbox text. https://i.sstatic.net/iTKoo.jp ...

Creating a dropdown menu that interacts with a specific element: step-by-step guide

TL;TR How can I achieve the following: getMyComponent(selectedMyComponentID).complexOperation() This seems like a simple and practical task, such as selecting an item from a dropdown menu. More Information Imagine that I am creating some sort of editor ...

Explore various THREE.JS 3D models through a clickable link

I am struggling to make each object open a new page using a URL when clicked. No matter what I try, it doesn't seem to work properly. Can someone point out what I might be missing or doing wrong? Here is the click event code for the objects. If needed ...

A bug in the modal dialog is causing it to disregard the value of

I want to transfer certain modal properties in this manner service.confirm = function(message, confirmProperties) { return $uibModal.open({ templateUrl: 'app/modal/alert/alert.tpl.html', controller: 'alertCon ...

The process of extracting all arrays from a JSON object

Within my JSON object, there is a list of countries each with multiple regions stored in an array. My goal is to extract and combine all the regions into one single list. However, when I attempt to map the data, it does not consolidate all the regions as e ...

Using PHP to convert JSON data into the Google Chart API

I am facing an issue with parsing my PHP generated JSON array into a Google chart. I have integrated JQuery, but for some reason, I am struggling to parse the JSON data. I execute a MySQL query to fetch data from the database. Then, I encode the query resu ...

Utilizing jQuery and AJAX, execute a PHP query based on the user's input and showcase the query's outcome without reloading the page

For the past 24 hours, I've been on a quest to find a solution. Although I've come across similar inquiries, either the responses are too complex for my specific scenario (resulting in confusion) or they are of poor quality. The crux of my issue ...

Guide to tallying the occurrences of a specific key within an object array and attaching the count to each key's current value

Is there a way to determine the number of occurrences of the 'value' key within an object that is part of an array, and then add the count to each value if applicable? In this case, 'a' represents the original data var a = [ { id: ...

Is there a way to include values in the body of an HTTP GET request using Angular?

I've created a function in my service that looks like this: /** * Retrieve all data * @param sendSelectedValues string */ getAllActPlanBalanceYearData(sendSelectedValues: any): Observable<any> { const url = `/yearlyvalues/act-and ...

There seems to be a glitch preventing Highchart from functioning within a jQuery function

Hello there! I'm currently utilizing the highchart API to generate graphs in a loop. for(i=1;i<10;i++) { xseries = "{'INCOPAV','B&M','SGS-ETSA'}"; yseries = "[{name: &apos ...

Fetching data in a post request seems to be causing an issue with FormData image being

I've implemented a profile picture file upload system with the following HTML: <form enctype="multipart/form-data" id="imageUpload" > <img id="profileImage" src="./images/avatar.png& ...

FancyBox - Is there a "Never show this message again" option available?

I implemented FancyBox on my website to display important information to users. However, I would like to enhance the user experience by adding a button that allows them to set a cookie and prevent the message from popping up for about a month. Since I&apo ...

Ways to detect the use of vue.js on a webpage without relying on vue-devtools

One way to determine if the page is utilizing Angular or AngularJS is by inspecting window.ng and window.angular. Is there a similar method to identify whether Vue is being used on the page directly from the console, without relying on vue-devtools? ...

Unable to include a JavaScript file within another JavaScript file

Currently, I am working on a project where I am utilizing Django for the backend and HTML/CSS/JS for the frontend development. On a specific HTML page, I am including two JS files: dom_creator.js and console_page.js. My goal is to access the functionaliti ...

Configuring Webpack for a React application with Express and Babel

I am in the process of developing a React application, utilizing React version ^15.6.1 along with Webpack, Express, Babel, and Yarn as the package manager. After successfully running the application, I am now preparing to transition it to production by co ...

Load page content dynamically with Ajax in a specific div while still allowing the option to open the content in a new tab by right-clicking

As I work on developing a new website that utilizes a MySQL database to sort various items into categories and subcategories, I have implemented a script that dynamically loads category content into a div without requiring a page reload. This seamless load ...

Ways to ensure that the form data stays consistent and visible to the user continuously

Is there a way to ensure that the user submits the form, stores it in a MYSQL database, and then displays the same submitted data in the form field? <div class="form-group"> <label class="control-label col-sm-2" for="lname">Last Name*</l ...

Transferring files with Node.js via UDP connections

I'm currently working on setting up a basic Node.js server that is designed to receive files from clients through UDP. The challenge I'm facing is that whenever I attempt to send a large file (anything over 100kb), the server appears unresponsive ...