How to Modify the Data in a Dynamic Object within the Vuex Store in a Nuxt Application

Within my Vue/Nuxt project, I have implemented a form where users can add and update dynamic fields for calculating price offers. Upon loading the form, one field is created using the beforeMount lifecycle, with the option for users to add more fields as needed.

My data return includes:

data() {
    return {
        calculationFields: { qty: 0, price: 3.86, selected: false }
    }
}

When the user clicks the "Add field" button, the addField method is triggered:

addField() {
    this.$store.dispatch('quantity/updateAdd', this.calculationFields)
},

The 'updateAdd' action calls the UPDATE_ADD_ITEM mutation:

UPDATE_ADD_ITEM(state, value) {
    state.options.push(value)
},

The template loops through the options array to display the specified number of fields:

<div v-for="(field, index) in getCalculationFields()" :key="field" class="flex-xs justify-between calculation-field">
    <InputCustomPlaceholder type="number" :is-required="true" :input-id="`calculation-${index}`" :input-name="`calculation-${index}`" label-text="" placeholder-text="Add pieces" custom-placeholder-text="pcs" extraclass="flex-1 no-margin" />

    <a href="#" class="remove-field" @click.prevent="removeField(index)">&times;</a>
</div>

However, I am facing an issue with implementing v-model on dynamically created input fields to update the 'qty' value in the options state object. I need to be able to update the quantity values for each corresponding field in the array.

If the list contains three fields like:

[
    { qty: 0, price: 3.86, selected: false }, 
    { qty: 0, price: 3.86, selected: false }, 
    { qty: 0, price: 3.86, selected: false }
]

For instance, if a user inputs a quantity of 200 for the second field, the updated array should look like this:

[
    { qty: 0, price: 3.86, selected: false }, 
    { qty: 200, price: 3.86, selected: false }, 
    { qty: 0, price: 3.86, selected: false }
]

I believe I need to utilize something like:

<InputCustomPlaceholder type="number" :is-required="true" :input-id="`calculation-${index}`" v-model="updateOptionList" :input-name="`calculation-${index}`" label-text="" placeholder-text="Add pieces" custom-placeholder-text="pcs" extraclass="flex-1 no-margin" />

But I am unsure about how to efficiently find the index of the field and update the corresponding value within the array. While in a non-dynamic input scenario, I typically use:

v-model="updateFieldOne"
updateFieldOne: {
    set(value) {
            this.$store.dispatch('fields/updatePartDimeWidth', value)
          }
}

Any guidance on the best approach to achieve this would be greatly appreciated.

Answer №1

If you assign the index prop and utilize it in mutation, the EDIT_ITEM mutation can assist with editing an item. To add a new element, you can use state.options.push(value).

this.$store.dispatch('fields/updatePartDimeWidth', {value ,index})

EDIT_ITEM(state, {value ,index }) {
    state.options[i] = value
  },

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

Organizing your code with precision

I'm struggling with a project due to the poorly formatted code, making it almost impossible to read. Despite my attempts with various plugins and tools in VIM, Netbeans, Sublime Text 2, and Eclipse, the situation only seems to worsen. If anyone has ...

Guide to seamlessly integrating form data into MySQL using JavaScript and HTML without redirecting the user from the current page

Having trouble inserting a new user into MySQL database? I've attempted using both jQuery and pure JavaScript, but it doesn't seem to be working. There's no response when I click on the submit button. Any ideas on what might be causing this ...

Fixing Timezone Issue in VueJs 3 with Axios POST Request

Having an issue with axios. In my application, I have an input field for datetime-local. When I select a date and time, the displayed time is correct (e.g., selecting 10:00 shows as 10:00), but when calling a function using axios.post, the request sends th ...

Using Javascript to Assign Value to Variables

I have been working on this code snippet: http://jsfiddle.net/9B84H/26/ function autosuggest() { var input = document.getElementById('location'); var options = {types: [],}; var autocomplete = new google.maps.places.Autocomplete(input, o ...

Tips for integrating Excel files with NestJS

I'm in the process of developing a REST API that will utilize a third-party API to retrieve specific status information. The URLs needed for this API are stored in an Excel file, which is a requirement for this use case. My goal is to extract the URLs ...

javascript mobile nav event

My website utilizes a bootstrap feature for mobile devices where a left sidebar pops up when clicking a button. I am not very familiar with bootstrap, but I would like to link a javascript event to determine if the left sidebar is visible. How can I achiev ...

Examining Resolver Functionality within NestJS

Today I am diving into the world of writing tests for NestJs resolvers. I have already written tests for my services, but now it's time to tackle testing resolvers. However, I realized that there is a lack of documentation on testing resolvers in the ...

Breaking down objects or arrays to extract specific values in React components

Some articles recommend using ES6 destructuring for React props & state as a best practice. For example: const { showModal, hideModal } = this.props; While I understand the benefits of cleaner code, I recently discussed with another developer who suggest ...

incorrect encoding of Greek characters due to the multer upload package

When uploading files with Greek characters, the uploaded titles are saved as ΠÏξ Îαξ & ÎαÏÏιμιÏαίοι Here is the code for multer variables inside a js file: const storage = multer.diskStorage({ destination: f ...

Ways to implement real-time search feature in Rails 4.2

Struggling to implement a basic search form with AJAX in my Rails 4.2 app, I've scoured numerous tutorials without success. Ruby on Rails Live Search (Filtering), https://www.youtube.com/watch?v=EqzwLUni2PM) This is the search method I'm usi ...

The color of the last clicked DIV is supposed to stay permanent, but for some unknown reason

I'm attempting to replicate this design in my project: http://jsfiddle.net/AYRh6/26/ However, I am facing issues with it and cannot pinpoint the exact problem in the code. I am using code for a toggle effect. Any assistance would be greatly appreciat ...

Can the height of one div be determined by the height of another div?

Here's the specific situation I am facing: I want the height of Div2 to adjust based on the content of Div3, and the height of Div3 to adapt based on the content in Div2. The height of Div1 is fixed at 500px. Some of the questions that arise are: I ...

Transforming an Angular 11 HTML template into Angular code

After attempting to transfer the Porto Admin HTML template to Angular, I encountered some issues. When including the CSS and JS dependencies in the project, everything worked fine with all the HTML code in index.html. However, when I moved the code to app. ...

Updating the node startup file with Visual Studio 2015 using NodeJS/Typescript

Encountering a persistent error: Error Code: TS5055 Cannot write file C:/project/dir/server.js' because it would overwrite the input file. Project: TypeScript/JavaScript Virtual Projects Even after renaming my entry filename to nodeserver.js, the ...

Is it possible to execute JavaScript within an Android application?

Is there a way to utilize the javascript provided by a website on an Android device to extract and analyze the emitted information? Here is the javascript code: <script type="text/javascript" src="http://pulllist.comixology.com/js/pulllist/5b467b28e73 ...

Passing props to child components in Next.js: A step-by-step guide

I am currently working with my index.js page, which incorporates a layout component: import Layout from "../components/layout"; export default function Home({posts}) { console.log(posts) return ( <Layout posts={posts}> & ...

Error on Laravel 7: Unable to retrieve resource - the server returned a 400 (Bad Request) status code

Seeking assistance with a technical issue involving Razorpay. I'm encountering difficulty passing a value from the controller to JavaScript in the view. The data-order_id field is not populating, resulting in the error mentioned above, indicating a nu ...

Creating a Loading State for CRUD Operations in Vue.js

In the process of creating my initial Vue.js application with Vuex, I am encountering obstacles when it comes to loading state correctly. Currently, I have a route dedicated to displaying all accounts (/accounts) and successfully loading the account data ...

Failure to deliver messages through socket.emit

Check out the following JavaScript code snippet: `var express = require('express'); var app = express(); var http = require('http').Server(app); var path = require("path"); var io = require('socket.io')(http); app.get(&apos ...

Using feature flags in Vue for enhanced functionality

I am interested in incorporating a "feature toggling mechanism" into my Vue application. Although I have set up a basic system, I want to explore the methods outlined in a article by Pete Hodgson. The concept of "Inversion of Decision" seems particularly i ...