Using Vuex's v-model to bind to a state field in an object

In my current Vuex state, I have defined a getter named configs, which looks like this:

configs: {
   1303401: {
       exampleValue: 'test'
   }
}

There is also an input where I bind the exampleValue from the Vuex store's state using v-model:

<input type="text" v-model="config.exampleValue" />

To handle this, here is the computed property set up to return the config:

config: {
   get () {
       return this.$store.getters.configs[1303401]
   },
   set (value) {
       // This section should update the configs[1303401] field with the new exampleValue
       this.$store.dispatch('UPDATE_CONFIG', value)
   }
}

While the input's value updates according to config.exampleValue, the Vuex state itself does not reflect these changes.

Furthermore, when attempting to console.log the value in the setter function, nothing is displayed in the console, indicating that the setter is not being executed at all.

This issue may be attributed to the fact that it is not setting the config computed property directly, but rather focusing on config.exampleValue. However, finding a solution for this has proven challenging.

A suggestion made by @asi-ple suggests modifying the getter to return configs[1303401].exampleValue, but this approach presents challenges as the config object contains multiple fields, and the page features several inputs. Implementing individual computed properties for each field would be impractical.

Answer №1

If you have multiple fields, there's an opportunity to incorporate logic.

Imagine having

configs: {
    1303401: {
        exampleValue: 'test',
        exampleValue2: 'test2',
        exampleValue3: 'test3',
        ...
    } 
}

You would need to adjust the template like this:

<input type="text" :value="config[1303401].exampleValue1" @input="update_config($event, 'exampleValue1')" />
<input type="text" :value="config[1303401].exampleValue2" @input="update_config($event, 'exampleValue2')" />
<input type="text" :value="config[1303401].exampleValue3" @input="update_config($event, 'exampleValue3')" />

Define your methods as follows

methods:{
    update_config($event, where){
          this.$store.commit("UPDATE_CONFIG", {value: $event.target.data, where: where})
    }
}

The mutation handler should appear like this

UPDATE_CONFIG(state, payload){
       state.configs[1303401][payload.where] = payload.value
}

In essence, by creating a config data in your state and utilizing two-way data binding in the template, you establish a structure for interaction. The inputs use :value as getters, @input listeners function as setters, update_config handles changes, and the mutation handler ensures they are correctly placed.

Answer №2

It seems that the issue lies in using v-model with an object property, causing the setter not to work properly. A simpler approach would be to only work with the property itself, as shown below in your computed property:

config: {
    get () {
        return this.$store.getters.configs[1303401].exampleValue
    },
    set (value) {
        this.$store.dispatch('UPDATE_CONFIG', value)
    }
}

Adjust your template accordingly:

<input type="text" v-model="config" />

This ensures that you receive the updated exampleValue in your store action. It is advisable to steer clear of using objects for getter/setter in computed properties when dealing with forms, as it can lead to unexpected issues.

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

Embedding a Three.js object within a div element that has disabled zoom functionality and prevents scrolling or zooming within

Recently, I started learning about three.js and currently find myself in need of some assistance. My goal is to set up my scene within a div element rather than the entire document without any zooming while still allowing the user to scroll using the mouse ...

Sending requests across domains from HTTPS to HTTP with callback functionality, and reversing the process

Prior to our conversation, I had created it using Flash. I uploaded a special file (crossdomain.xml) on the server side (https), while the Flash component was placed on the http server. Although they belong to different domains on the https and http serv ...

Is there a way for me to specifically show just the initial image contained in the images[] array within the json data?

{"status": true, "data": {"basic": {"dob": "2018-02-02", "gender": "male", "contact": {"address": null}, "is_new": false, "is_email_verified": false, "is_phone_verified": false}, "listings": [{"pid": 109, "category": {"name": "Education"}, "location": {"l ...

How to Convert JSON from an Object to a String using jQuery?

Currently, I am utilizing the Ajax Form jQuery plugin to fetch JSON data from a server: /** * A convenient function for the jQuery AJAX form plugin. */ function bindOnSuccess(form, callback) { form.ajaxForm({ dataType: 'json', ...

What is the method for integrating my SVG icons with q-btn-toggle?

I'm currently integrating SVG icons into my project using Quasar and I am facing an issue with the q-btn-toggle component. The documentation suggests providing a direct path to the SVG file, but in reality, the icon does not display. Below is a snippe ...

Using AJAX to communicate with a MySQL database and create a countdown timer using JavaScript

I have been trying to display data from a database using Ajax and incorporate countdown timers with times also fetched from the same database. It has been a struggle for me for almost 24 hours now. You can check out the main code here where you will notic ...

I am wondering if it is feasible for a POST route to invoke another POST route and retrieve the response ('res') from the second POST in Express using Node.js

Currently, I have a POST route that triggers a function: router.route('/generateSeed').post(function(req,res){ generate_seed(res) }); UPDATE: Here is the genrate_seed() function function generate_seed(res) { var new_seed = lightwallet. ...

Angular.js controller unable to receive object array from $http.get in factory

I am fairly new to Angular development and I've hit a roadblock that's been holding me back for a while. My factory is successfully creating an array filled with objects, specifically RSS feed data, and I can see it loading in the console. Howev ...

When executed through nodeJS using the `require('./main.ts')` command, TypeScript Express encountered an issue with exporting and displayed undefined

Describing my issue is proving to be challenging, so I have simplified the code. Let me share the code below: main.ts import express from 'express'; let a = 1 console.log ('a in main.ts', a) export let b = a const app = express() let ...

Utilizing children as a prop within a Vue component

In React, I can create a FancyList component like this: const FancyList : React.SFC<{},{}> ({children}) => ( <ul> {...children} </ul> ); const FancyListItem : React.SFC<{text: string}, {}> ({children}) => < ...

What is the process of configuring a custom domain for localhost:3000 in a React application?

"scripts": { "start": "cross-env NODE_PATH=src react-scripts start", "build": "cross-env NODE_PATH=src react-scripts build", } Is there a way to replace localhost:3000 with a custom domain in Rea ...

Rzslider not functioning properly due to CSS issues

I am facing an issue where rzslider is not appearing in my app. However, when I copy the code to an online editor, it works perfectly fine. Below is the code snippet: var app = angular.module('rzSliderDemo', ['rzModule', 'ui.boo ...

What is the best way to display a multi-state component that includes an API fetch?

Currently, my tech stack includes React and Node.js. Within my project, I have a component named ItemList. This particular component fetches data from an API in the componentDidMount() method to facilitate rendering a "loading state." My objective is to ...

Retrieving a specific time using a JavaScript interface

I am currently implementing a JavaScript control that can be found on this website: My question is, how can I retrieve the selected date from the control in order to pass it to a postback page? I attempted to figure it out myself, but my JavaScript skills ...

Having to click the update button multiple times for a Vue-chartjs chart with method parameter can be

In an attempt to enable users to display different charts by sending the id of the chosen chart to the fillData method, I have encountered several issues with the current code. One problem is that after a chart is loaded, it requires two clicks of the othe ...

Do not fetch data again after a re-render

My code is facing an issue where every time I click toggle, the Child component re-renders and triggers another API request. My goal is to fetch the data once and then keep using it even after subsequent re-renders. Check out the CodeSandbox here! functio ...

The process of converting a data:image base64 to a blob is demonstrated in this code snippet

Seeking a way to convert data:image base64 URLs to blob URLs. Below is the original code that generates the base64 URLs: <script> $(window).load(function(){ function readURL() { var $input = $(this); var $newinput = $(this ...

Configuring environment variables in Vue CLI

When using webpack, I found a way to set environment variables in my package.json as shown below: "scripts": { "dev:visualise": "webpack serve --open --config webpack.dev.js --env entry=visualise", "dev:order": & ...

The timing calculations in Vue.js do not align with the standard JavaScript version

I am currently working on developing a 'beats per minute' (BPM) calculator, which is similar to the one available here. However, I have noticed that when using the BPM calculator from that link for testing on a particular song, it quickly approxi ...

Why is only the peak of the wave visible? I am eager to showcase the full extent of its beauty

Having an issue with the appearance of a superposed wave using threejs. When displayed, the wave made from plane material only shows the upper half, but when turned upside down using mouse dragging, it appears correctly. // Turn the wave plane upside down ...