Instead of using a computed getter/setter, make use of mapState and mapMutations to simplify

Currently, I am syncing a computed value to a component and using a computed setter when it syncs back from the component.

I'm wondering if there is a more concise way to replace a computed getter/setter with mapState and mapMutations. How can this be achieved in a more compact manner?

<template>
    <SomeComponent :value.sync="globalSuccess"></SomeComponent>
</template>
export default {
    //...
    computed: {
        globalSuccess: {
            get() {
                return this.$store.state.globalSuccess;
            },
            set(val) {
                this.$store.commit("globalSuccess", val);
            }
        }
    }
}

I attempted to replace it like so:

export default {
    //...
    computed: {
        ...mapState(["globalSuccess"]),
        ...mapMutations(["globalSuccess"]),
    }
}

However, mapMutations(["globalSuccess"]) interprets this.globalSuccess(value) as

this.$store.commit('globalSuccess', value)
based on the documentation of vuex.

Since my computed value is set internally with globalSuccess = true through :value.sync in the template and not this.globalSuccess(true), globalSuccess remains unset.

Do you have any suggestions on how to make this work differently? Or do I have no choice but to stick with computed values utilizing getter and setter?

Answer №1

Recently, I came across a fantastic vuex module called https://github.com/maoberlehner/vuex-map-fields. Intrigued by its functionality, I followed the installation steps provided:

// store.js
import { getField, updateField } from 'vuex-map-fields';
Vue.use(Vuex);
export default new Vuex.Store({
    getters: {
        getField,
        //...
    },
    mutations: {
        updateField,
        //...
    },
});

After setting up the module, I utilized the mapFields function in my component like so:

// App.vue
export default {
    //...
    computed: {
        ...mapFields(["globalSuccess"]),
    }
}

Through this implementation, I was pleased to see that it dynamically mapped to a computed setter and getter exactly as desired:

export default {
    //...
    computed: {
        globalSuccess: {
            get() {
                return this.$store.state.globalSuccess;
            },
            set(val) {
                this.$store.commit("globalSuccess", val);
            }
        }
    }
}

Answer №2

Here is a code snippet that I find useful:

export default {
  //...
  computed: {
    globalSuccess: {
      ...mapState({ get: 'globalSuccess' }),
      ...mapMutations({ set: 'globalSuccess' }),
    },
  },
}

No external dependencies required. If this code snippet is used frequently, it might be beneficial to create a helper function for it, but in its current form, it works quite effectively.

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

Typescript counterpart of a collection of key-value pairs with string keys and string values

Within the API I'm currently working with, the response utilizes a data type of List<KeyValuePair<string, string>> in C#. The structure appears as shown below: "MetaData": [ { "key": "Name", &q ...

Frontend update: Changing the display format for dates

Received from the backend is an array of objects (leavedays)- var leavedays = [{"_id":"62d544ae9f22d","season":2022,"name":"LEAVEDAY1","dateFrom":"2022- 07-26T00:00:00.000Z","date ...

Creating a multi-dimensional array using information from a database

I have a unique challenge where I am utilizing a template that generates a menu with a specific structure. In my database, I have various menus stored and I've successfully retrieved them. However, the issue arises when I need to figure out a way to d ...

To ascertain whether the mouse is still lingering over the menu

I have a condensed menu construction that unfortunately cannot be changed in HTML, only CSS and JS modifications are possible! $('span').on("hover", handleHover('span')); function handleHover(e) { $(e).on({ mouse ...

Parsing JSON sub items in Android application using Java

Here is a snippet of my PHP file: <?php $myObj = array( "name"=>"John" , "age"=>"30" , "post"=>[ "title"=>"What is WordPress" , "excerpt"=>"WordPress is a popular blogging platform" , ...

Angular Material's md-checkbox is a required component

I am working on a form that consists of checkboxes representing the days of the week. When the user hits submit without selecting any checkboxes, I want an error message to appear. Here is the HTML code snippet that I have: <form id="addEditForm" nam ...

Sorting nested table rows in vueJS is an essential feature to enhance

I am working with a json object list (carriers) that looks like this: https://i.stack.imgur.com/0FAKw.png Within my *.vue file, I am rendering this using the following code: <tr v-for="carrier in this.carriers"> <td>{{ carrier.id ...

React Scroll and Material-UI button active link not functioning correctly

Whenever the link goes to the correct page, I want to add a special background effect or change the font color. Despite trying to use CSS for this purpose, it didn't work as intended. If you want to take a look at my code on codesandbox, follow this ...

Shut down the tab or browser window containing information on vue

When attempting to log off a user by closing the page and browser, I encountered difficulty. 1. window.onunload; 2. window.onbeforeunload. window.onunload = function() { differTime = new Date().getTime() - beginTime; if (differTime <= 5) { cle ...

Error encountered in Angular 7.2.0: Attempting to assign a value of type 'string' to a variable of type 'RunGuardsAndResolvers' is not allowed

Encountering an issue with Angular compiler-cli v.7.2.0: Error message: Types of property 'runGuardsAndResolvers' are incompatible. Type 'string' is not assignable to type 'RunGuardsAndResolvers' This error occurs when try ...

Dealing with error management in Transfer-Encoding chunked HTTP requests using express and axios

My current challenge involves fetching a large amount of data from a database in JavaScript using streaming to avoid loading all the data into memory at once. I am utilizing express as my server and a nodeJS client that retrieves the data using Axios. Whil ...

Leveraging Variables within my .env Configuration

Does anyone have suggestions on how to set variables in my environment files? Website_Base_URL=https://${websiteId}.dev.net/api In the code, I have: websiteId = 55; and I would like to use config.get('Website_Base_URL'); to retrieve the compl ...

How can I create a dropdown menu that is dependent on another dropdown menu using Ajax in my Laravel application?

I have two dropdown fields that are dependent on each other - Class & Section. I am trying to Select * from sections where class_id=selected Class Id. Although I attempted to achieve this using java script, it doesn't seem to work for me. Here are ...

Encountering an issue with Nuxt 3.5.1 during the build process: "ERROR Cannot read properties of undefined (reading 'sys') (x4)"

I am currently working on an application built with Nuxt version 3.5.1. Here is a snippet of the script code: <script lang="ts" setup> import { IProduct } from './types'; const p = defineProps<IProduct>(); < ...

Arrange the div and ensure that the external JavaScript file functions properly when the page loads

I am encountering an issue with my JavaScript and CSS code. It works perfectly fine within the fiddle environment but fails to function properly outside of it. Here is the link to the fiddle When I embed the code into an HTML document directly, it does n ...

Nested Promises in Angular's $q Library

I'm facing an issue with a function that should return a list of favorite locations. Here's the code snippet in question: When I call LocationsFactory.getFavoriteLocations(), it returns a promise like this: getFavoriteLocations: function() { ...

Partially Assessed Ajax Response

I am struggling with my ajax response as it seems to evaluate only some of the html, but not all of it. For instance, I have this code that replaces a div with the response from the request: eval(document.getElementById("test").innerHTML-xmlhttp.response ...

The route in my Node.js Express application appears to be malfunctioning

I am facing an issue with my app.js and route file configuration. Here is my app.js file: const express = require('express'); const app = express(); const port = process.env.PORT || 8080; const userRoute = require('./routes/user.route' ...

Developing a fresh Outlook email using a combination of javascript and vbscript

I have created a custom HTML page with fields and a button to fill out in order to generate a new Outlook mail item. To format the body of the email using HTML, I am utilizing VBScript to create the new mail item. <script> function generateEmail() { ...

The functionality of Bootstrap Tabs is compromised when used within a jQuery-UI dialog window

My goal is to develop a user interface similar to MDI for my application. To achieve this, I am utilizing the dialog feature of the jQuery UI library. To dynamically create a dialog window on demand, I have coded a helper function as shown below: functio ...