Utilize vuex v-model to define the value of an object component

Coordinating input elements with object keys in Vuex state is my current challenge. Imagine I have this object:

myObj: { foo: 1, bar: 2 }

Within a component, I have a computed property set up like so:

myObjVals: {
  get(){ return this.$store.state.myObj },
  set(//?) { //? },
},

In the template, accessing values from the store works fine:

<input type="number" v-model="myObjVals['foo']"/>  // shows "1"
<input type="number" v-model="myObjVals['bar']"/>  // shows "2"

However, trying to modify the value of an input triggers the error message: "Do not mutate vuex store state outside mutation handlers."

One solution would involve creating a dedicated computed property for each key in myObj, but this approach becomes cumbersome for larger objects. I'm exploring if it's possible to achieve the same functionality as described above using just one computed property to handle both the get and set functions in v-model.

Answer №1

Consider revisiting your issue. One potential solution could be found in this resource: https://vuex.vuejs.org/guide/forms.html

<input type="number" :value="myObjVals['foo']" @input="changeMyObj('foo', $event)"/>  // shows "1"
<input type="number" :value="myObjVals['bar']" @input="changeMyObj('bar', $event)"/>  // displays "2"

Utilizing computed property and a method:

computed: {
    myObjVals: function () {
        return this.$store.state.myObj
    }
},
methods: {
    changeMyObj(key, evt) {
        this.$store.commit('changeMyObj', {key: key, value: evt.data})
    }
}

Implementing a mutation within the store:

mutations: {
  changeMyObj(state, objInput) {
    state.myObj[objInput.key] = objInput.value
  }
}

Check out this functional example on JSFiddle: http://jsfiddle.net/zfab6tzp/346/

While not definitive, this appears to be a viable solution for now.

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

Adding the highcharts-more.src.js file to an Angular 2 project: A step-by-step guide

I have linked highcharts-more to the system variable: 'highcharts-more': 'node_modules/highcharts/highcharts-more.src.js' But I keep getting an error message saying: Error in dev/process/templates/detail.template.html:40:33 ORIGINAL ...

"Enhance Your Website's User Experience with jQuery Aut

One of the challenges I am facing involves an Ajax call that retrieves a JSON representation of data created using PHP's json_encode method: ["Montérégie","Montréal - North Shore","Montréal - South Shore"] These values are extracted from a &apos ...

In JavaScript, what is the best way to target the initial option element in HTML?

As a newcomer to javascript, I'm wondering how to target the first option in the HTML <option value="">Choose an image...</option> without altering the HTML itself? My thought is: memeForm.getElementById('meme-image').getElement ...

Implement the administration sw-media-quickinfo functionality within the Shopware 6 platform

Is there a way to incorporate administrative action in this https://i.stack.imgur.com/EviNq.png? I am aware that I need to either override or extend the component, but how do I determine the correct one and what should be included in the second override a ...

Memory leakage in Internet Explorer as a result of JavaScript code

Recently, I created a website that utilizes jquery ajax to send an ajax request every minute in order to retrieve json data. This data is then parsed and added into the DOM. While this process runs smoothly on Chrome and Firefox, I noticed a significant m ...

Determining the exact position on a graph by calculating its value along the line of best fit

After analyzing the following dataset - | a | f | |-----------|---------| | £75.00 | 43,200 | | £500.00 | 36,700 | | £450.00 | 53,400 | | £450.00 | 25,700 | | £250.00 | 12,900 | | £1,600.00 | 136,000 | | £600.00 | 7 ...

Creating mp4 files from a sequence of jpg images using Node.js

My server continuously receives jpg files from a client. The challenge at hand is: how can I create one mp4 file using all of these jpg files? I currently save all the jpg files and then utilize ffmpeg with “filename%3d.jpg” once the client finishes s ...

Is there a way to automatically redirect my page after clicking the submit button?

I'm having trouble with the code below. I want it to redirect to NHGSignin.php if 'new horizon gurukul' is entered. When I click the Next button, it's supposed to take me there but it's not working as expected. Can anyone help me f ...

What is the best way to create a toggle button that can show more or show less of a text snippet with animation?

Is it possible for someone to assist me with showing a long text partially and providing a "show more" button to reveal the rest, along with a "show less" option, all with some CSS animation? I was thinking of using a font awesome arrow down icon for expan ...

Target only the <a> elements within a specific <div> using JavaScript

How can I target the first occurrence of the letter 'a' in this code using JavaScript? (href=some.php) <div class="accordionButton"><div id="acr_btn_title"><a href="some.php"><p>stuff</p></a></div><di ...

Angular2 Event:keyup triggers the input to lose focus

I am working on a component with an input element that is bound to a property. I want the input field to update in real time as I type in it. Here is my current code: <input type="text" #updatetext [value]="item.name" (keyup)="updateItem(item.$key, up ...

Top choice for recording sound and video over the internet

Seeking assistance in finding solutions to enable recording audio and video via web on different platforms such as iPhone and iPad. The recorded media needs to be saved on the server. Any recommendations for a cross-browser compatible approach are apprecia ...

Displaying individual attributes of objects through v-for loop

I have created a table-making component to streamline the process of creating multiple tables. Each table consists of three key elements: The object (an array of objects with one row per object) Headers specific to each table The object properties that n ...

What is the best method for passing information to my frontend JavaScript files using Express?

When using ejs to render my html pages, I pass in data in the following manner: collection.find({}).toArray( function (err, results) { res.render('index', { results: results, ...

Error: export keyword used incorrectly

Currently, I am in the process of developing an npm package called foobar locally. This allows me to make real-time changes and modifications without the need to constantly publish and unpublish the package, which greatly improves my development efficiency ...

Enabling block scrolling on a parent element using jscrollpane functionality

Is it possible to set up a jscrollpane so that the parent pane doesn't scroll when the child scroll has reached its bottom? Currently, when the child scrolling reaches the bottom, the parent also scrolls. I would like the parent to only scroll when th ...

Dynamically setting the default selection in a dropdown menu

When choosing a default value from a dynamically populated dropdown using JSON data, I attempted to use regCtrl.screeningTypeList[0] without success. <select ng-init="regCtrl.user.screeningType.screeningTypeId=regCtrl.screeningTypeList[0]" ng-model="re ...

When utilizing jQuery lightbox to pull data from a database using PHP/Ajax, it may require a double click the

Encountering a strange issue where I must click on specific buttons with unique IDs. These IDs are then sent through Ajax to a PHP script, which searches for corresponding entries in the database. The retrieved data is then displayed in a jQuery lightbox. ...

Tips for avoiding template errors when retrieving data using Nuxt's fetch() method

After transitioning my vue app to a nuxt app, I encountered an issue with vue-slick-corousel. In the original vue app, everything worked smoothly with vue-slick-carousel, but after making the necessary modifications for nuxt, the carousel wouldn't dis ...

The spinal cord of design inquiry

I am currently working on a Backbone view called MainMenuView. Within this, the MainMenuModel consists of an array of sub-models known as ItemModel. The main menu is divided into two pages and includes next and previous buttons for navigation. The first pa ...