Using mappers to create a computed property for two-way binding

In my Vue 2 project, I make use of vuex.

Currently, I am working on implementing two-way binding for this HTML element:

<input v-model="message">


computed: {
  message: {
    get () {
      return this.$store.state.obj.message
    },
    set (value) {
      this.$store.commit('updateMessage', value)
    }
  }
}

My aim is to use mappers within the get and set methods for cleaner code:

computed: {
  message: {
    get () {
      return ...mapState("obj", ["message"])
    },
    set (value) {
      ...mapMutations("obj/updateMessage", value)
    }
  }
}
    

However, I encounter errors on two lines:

return ...mapState("obj", ["message"])   -   Expression expected.

...mapMutations("obj/updateMessage", value) - Declaration or statement expected.

Is there a way to successfully use mappers within the get and set methods?

UPDATE: I have already imported mapMutations and mapState to the component.

Answer №1

To begin, make sure to import the necessary elements, similar to how you imported Vuex with

import { mapState, mapActions } from 'vuex'
. Remember to import actions specifically, rather than mutations. Actions are asynchronous and the correct flow should always be to dispatch an action > commit a mutation > update the state.

Next, integrate these imports where they are needed:

computed: {
  ...mapState('obj', ['message']),
  // other computed properties ...
}

methods: {
  ...mapActions('obj', ['updateMessage']),
  // other methods ...
}

Now, onto the interesting part:

computed: {
  message: {
    get () {
      const cloneDeepMessage = cloneDeep(this.message)
      // potentially destructure here like >> const { id, title, description } = cloneDeepMessage
      return cloneDeepMessage // or if destructured some fields >> return { id, title, description }
    },
    set (value) {
      this.updateMessage(value)
    }
  }
}

It's advisable to also

import cloneDeep from 'lodash/cloneDeep'
to prevent direct state mutation by using cloneDeep when accessing state. This is a precaution emphasized by Vuex strict mode, which I suggest enabling solely during development.

The official documentation may not explicitly cover this aspect, but it's a recommended approach in my opinion, drawing from various corresponding sections and combining them 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

Creating a sorting function in VueJS requires a few key steps

I'm working on implementing a sorting function in my VueJS code that includes the following options: Price: Low to High, Price: High to Low. Here is my template: <div name="divSortBy"> <span> Sort by: & ...

Is there a way to create a dynamic gallery using Magnific Popup that showcases both images and an iframe video together?

One way I am utilizing magnific popup is to set up an image gallery using the code snippet below: $('.main-content').magnificPopup({ delegate: '.gallery', // selecting child items to open in pop-up when clicked type: 'image&ap ...

The information provided has been cut off: 1406 The content exceeds the permitted length for the 'image' column in row 1

Whenever I select a random image, the name turns out to be very long despite being a varchar data type. Here is my migration file: $table->id(); $table->string('image'); $table->timestamps(); This code snippet shows my image ...

Is it possible to hide a menu by removing a class when the user clicks outside the menu?

I've come across a lot of information about how to close a menu when clicking outside of it, but my question is, can the following code be simplified to something like if you don't click on #menu > ul > li > a then removeClass open. Can ...

Can you please identify the TypeScript type associated with the return value of the match() method in String prototype?

I need help with creating a Regex in JavaScript const pattern = /S(\d+)E(\d+)/; // identifying characters between "S" and "D" const result = 'SE01E09'.match(pattern); How should I declare the result variable? I have attempted various ...

Issues with location forecasts and .getPlace() when utilizing the Google Maps loader for Place Autocomplete in Vue are causing functionality problems

After setting up a Vue 2 app using the vue cli, I noticed that when typing an address, no suggestions were populating from the dropdown. Checking the network tab, I observed the AutocompletionService.GetPredictions call triggering without any errors upon p ...

Sorting and dividing an Array using Angular

Forgive me in advance if this sounds like a naive question, as Angular and Typescript are not my strong suits. I am assisting a friend with an issue that I can't seem to overcome. I have an array of players that includes details such as first name an ...

Stop mega menu items from disappearing when hovered over

I'm currently working on a web page that features a mega menu. When I hover over the mega menu, it displays its items. However, when I try to hover over the items, they disappear. Here is the HTML code snippet: <li class="dropdown mega-dropdown m ...

Deploying an AngularJS 1.x application bundled with Webpack to Tomcat server

I've scoured the depths of Google and combed through the official documentation for Webpack, but I’ve yet to stumble upon a tutorial, guide, or plugin that addresses this particular issue. Does anyone have any experience with this problem, or should ...

Passing a parameter from a redirect function to an onClick in React using TypeScript

I am facing a challenge in passing a parameter to my redirectSingleLocker function. This function is intended to take me to the detailed page of a specific locker, identified by a guid. The lockerData.map method is used to display all the JSON data in a ta ...

Having issues extracting information from easports.com due to difficulties with the <ea-elements-loader> element

Recently, I've been developing a Python WebScraper to extract data (such as wins and losses) from our FIFA ProClub by crawling various websites. While I successfully implemented it on a third-party website using BeautifulSoup and requests, I encounter ...

Updating image URL for grouped objects with Fabric JS

Check out this link :http://jsfiddle.net/mishragaurav31/ang58fcL/#base I created two groups of objects; one consisting of a circle and text, and the other with two images. When I try to change attributes for group 1, it works fine. However, when attempt ...

Tips for extracting and utilizing a JSON object provided by the parent page:

Sorry in advance if this question has already been addressed. I've spent hours searching on Google, but haven't found a satisfactory answer yet. Below is the code snippet I'm working with: <ion-content> <div class="list"> ...

Is there a way to get rid of the tiny black line beside the Instagram icon?

Here is the display on my website This is the code that was used I am struggling to identify the source of the small black "-" line next to the Instagram icon logo. ...

The functionality of JQuery fails to work properly when receiving an AJAX response

I have separated my code into three main sections: a PHP file, a jQuery section with an AJAX function that requests data, another PHP file. The response from the AJAX request is HTML that needs to be added at the beginning of a specific DIV inside the i ...

What could be causing the JSON output to appear in a disordered fashion?

I am attempting to retrieve weather information for 8 different locations. Utilizing a weather API that requires longitude and latitude, it returns JSON output with the weather data for each location. I provided the coordinates in sequential order from 0 t ...

If the if logic in Express.js fails to function properly, it will consistently output the same message

Every time I run this code, it always displays the same message, even when I input different email addresses let message = ""; const findQuery = "select email from Users where email = ?"; const queryResult = await db.query(findQue ...

What is the reason behind JavaScript's restriction on using double comparison operators?

What is the reason behind javaScript not supporting double comparison? For example, in 64 < str.charCodeAt(i) && str.charCodeAt(i)<=77, why is it not possible to simplify it to 64 < str.charCodeAt(i)<=77? ...

What are your thoughts on the combination of Vue.js and Codenvy

I have been attempting to set up a basic Vue.js workspace, but everything I try seems to be unsuccessful. Whether I build it from scratch or use a Git repository, nothing seems to work at all. Is it even possible to get it to work? To Reproduce: Create ...

Object is not compliant with HTMLInputElement interface and cannot execute 'stepUp'

Currently, I am facing an issue with passing the selected value from a dropdown list of countries to a PHP file using AJAX. The goal is to take this value and then transfer it to another input field identified by the ID #tele. Here is the gist of my code: ...