Unraveling Complex Data and Generating Distinct Identifiers with Vue

After reading about normalizing complex data, I am facing a challenge with creating new objects and accessing them by their unique IDs in a component that is generated on the click of a button. I need to be able to assign these new objects to my parent object and normalize the data for potentially hundreds of unique budget row objects. Any guidance on how to achieve this would be greatly appreciated as I find it difficult to apply the information from forum posts to my specific situation.

Vue Forums Vue Forum Post 2

state: {
// Current state of the application lies here.
// budgetRows array at webpage load, base state
budgetRows: {}

},
getters: {
    // Compute derived state based on the current state. More like computed property.
    // Gets budgetRows array from state
    budgetList: state => {
      return state.budgetRows
    },
// should get single array items from budgetRows based on component being accessed
budgetListItem: state => {
  return state.budgetRows
}


},
  mutations: {
    // Mutate the current state
    // Used to create a new row and push into budgetRows array (generate uniq id as well)
    createRow (state) {
      const uid = uniqId()
      Object.assign(state.budgetRows, {[uid]: defaultRow})
      // console.log(state.budgetRows)
    },

Child Component:

 <div v-for="(budget, index) in budgetRowsList" :key="index">
      {{ index }}
      <budgetItemRowContent></budgetItemRowContent>
      <progress data-min="0" data-max="100" data-value="20"></progress>
    </div>
  </div>
</div>
<footer class="budgetGroupFooter">
  <div class="budgetGroupFooter-Content budgetGroupFooter-Content--Narrow">
    <button class="addBudgetItem" id="addBudgetItem" v-on:click="createNewContent()">
      <svg xmlns="http://www.w3.org/2000/svg" width="8" height="8" viewBox="0 0 8 8">
        <path fill="#FD0EBF" d="M3 0v3h-3v2h3v3h2v-3h3v-2h-3v-3h-2z"></path>
      </svg>
      Add Item
    </button>
  </div>
</footer>

<script>
import budgetItemRowContent from '../components/budgetItemRowContent.vue'
import { store } from '../store'

export default {
  name: 'budgetGroup',
  components: {
    budgetItemRowContent,
    store
  },
  data: () => {
    return {
      budgetItemHeading: 'Housing'
      // creates array containing object for budget row information
    }
  },
  computed: {
    budgetRowsList () {
      return this.$store.getters.budgetList
    }
  },
  methods: {
    createNewContent () {
      this.$store.commit('createRow')
    }
  }
}

On load of webpage, both label and other input will edit, inputbudget and amountbudgeted respectively

On two clicks, two more child components are created with unique ids

Answer №1

Utilizing Vue.set is the recommended approach for incorporating new properties into an existing object, with Object.assign being another option:

import Vue from 'vue'

// defining the initial state of an object
const defaultRow = {
  inputBudget: '',
  amountBudgeted: 0,
  remaining: 0
}

const state = {
  budgetRows: {}
}

const mutations = {
  createRow (state) {
    const uid = uniqId()

    // using Vue.set
    Vue.set(state.budgetRows, uid, defaultRow)

    // alternatively, with Object.assign()
    Object.assign(state.budgetRows, { [uid]: defaultRow })
  }
}

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

Error: Unable to locate bundle.js when attempting to refresh the page with a specific ID in the URL

I encountered an issue where I tried redirecting a user to their profile page to display the profile information corresponding to it. Let's say we have http://localhost:8080/user/1 as an example. Upon redirecting the user using the navbar link, the pa ...

Having difficulty deleting an entry from a flatList in a React Native component when using the filter method

I'm currently facing an issue with deleting an item from my flatlist in React Native. I've been attempting to use the filter method to exclude the list item with the ID entered by the user for deletion, but it's not working as expected. I&ap ...

The argument for the e2e test is invalid because it must be a string value

Currently, I am conducting an end-to-end test for an Angular application using Protractor. However, I encountered an error while running the test for a specific feature file. The UI value that I am checking is - WORKSCOPES (2239) Below is the code snippe ...

Using a regular div to display a modal - Reactstrap

Exploring the possibilities with a Reactstrap Modal: Modal - Reactstrap I am curious about integrating this modal seamlessly into a page layout, similar to a regular div. For example, having the modal display on the page without the animation effects and ...

Can you suggest a way to revise this in order to include the type of property (string)?

Here is a snippet of working code that raises a question about refactoring to improve the readability and functionality. Consider renaming the method to isPropValueSame. import * as _ from 'lodash'; const diff = _.differenceWith(sourceList, comp ...

What is the best way to bring icons into a Laravel + Vue.js project?

I recently encountered an issue while trying to import Fontawesome icons into Vue.js in Laravel. I managed to successfully import the Spinner icon as per a tutorial. However, I'm now wondering how I can find the names of other Fontawesome icons or if ...

Retrieve returned data using jQuery

How can I retrieve data when using the jQuery.get method? function send_data(pgId) { for(var i = 0; i < pgId.length; i++) { // $.get(url, data, success(data, textStatus, jqXHR)) $.get('index.php?page=' + pgId[i], pgId[ ...

Hiding a button based on the visibility of another button in the user's viewport

Is there a way to dynamically hide button B when the user scrolls and button A becomes visible on the screen? Additionally, how can we show button B again once button A is no longer visible to the user? Both buttons should never be visible simultaneously. ...

What is the method for ensuring that the state and component have identical values?

Currently, I am diving into the world of UI design using the React library. However, I seem to be encountering some issues with my code. handleIncrement = () => { this.setState({ ...this.state, quantity: this.state.quantity + 1 }) ...

What is the method for defining distinct parameters for nested functions in AngularJS?

When using AngularJS, what happens when a parent function encapsulates a child function that includes parameters not present in the parent? In this scenario illustrated below with the green arrow representing the parent function without any parameters, an ...

Executing ng-click to access outer controller from within nested ng-controllers

I'm exploring the potential of using angularjs to develop a dynamic page with the following capabilities: It starts off blank, except for a dropdownlist that automatically populates with various apps. Upon selecting an app from the list, relevant da ...

Choosing between Vue.prototype, Vue.use, and import for each fileWhen it comes

Discover various techniques for implementing a global function in a Vue.js project: time.js // Option 1: if using Vue.use() export default { install: Vue => { Object.defineProperty(Vue.prototype, "time", { return new Date().getT ...

Preventing typing during onKeyDown event in React/JavaScript and other languages

One of the reasons why I opt to use onKeyDown is because the language for typing is Korean. With multiple inputs on the page, my aim is to prevent users from typing more than 20 bytes. //this function calculates the byte length const getByteLength = (s,b ...

JavaScript fails to function properly on FireFox

I'm currently troubleshooting a script that works in Chrome but not in FireFox. I suspect it's due to the webkit syntax, so I tried converting it to a standard gradient without success. Can you help me identify what's causing the issue? Web ...

At what point does the event loop in node.js stop running?

Could you please enlighten me on the circumstances in which the event loop of node.js terminates? How does node.js determine that no more events will be triggered? For instance, how does it handle situations involving an HTTP client or a file reading app ...

Fetching data dynamically from the server using AJAX for a interactive chart with Flot

After looking at the Flot reference, they mentioned, The plot function can also be used as a jQuery chainable property. Is it possible to configure the Flot chart in this way? var pid = ''; var kid = ''; var chartasset; $(documen ...

Adjust image size as the page is resized

My challenge is to resize images that are typically too large for the current window size, ensuring they fit within 85% of the client window. I tried creating a function utilizing onload and onresize events but encountered issues. function adjustImages(){ ...

Nuxt was unable to locate the module @nuxt/ufo in the /app/client directory. There were no modifications performed

After restarting my docker image running a nuxt application today, I encountered a new error that I hadn't seen before. It is showing the following message: ERROR Cannot locate module '@nuxt/ufo' in '/app/client' ...

The subscriber continues to run repeatedly, even after we have removed its subscription

The file brief-component.ts contains the following code where the drawer service is being called: this.assignDrawerService.showDrawer(parameter); In the file drawer-service.ts: private drawerSubject = new BehaviorSubject<boolean>(false); public ...

Stop the page from automatically scrolling to the top when the background changes

Recently, I've been experimenting with multiple div layers that have background images. I figured out a way to change the background image using the following code snippet: $("#button").click(function() { $('#div1').css("background-image ...