Spontaneously generating models

Explaining this concept can be a bit complex. I am tasked with creating an object that contains properties from dynamic HTML code. To illustrate, let's use an example:

Firstly, here is my data object:

var myObject = {Field1: 'Value1', Field2: 'Value2'};

Next, I have an array listing the properties of my object like so:

var myArray = ['Field1', 'Field2'];

I then utilize this array to generate <input> elements in a for loop:

<div v-for="property in myArray">
    <input type="text" :value="myObject[property]" />
</div>

The challenge at hand is retrieving the values from these dynamically generated inputs, either as an object or an array.

While it may seem straightforward to just grab myObject, the issue arises when the input values change (since they are user-modifiable). We also want to avoid directly binding the inputs to myObject, as we need myObject to stay in its original state even if the input values are altered.

My question is, how can I create a new object and bind my inputs to that newly created object?

Answer №1

Here are some possible solutions:

  1. Utilize v-model for one computed value, but note that Vue may not detect modifications for re-rendering.

  2. Create a clone of myObject and watch it for changes, triggering actions as needed.

  3. A variation of solution 2 involves using v-bind to assign values from input events to another object or target. Note that v-model performs a similar function.

const app = new Vue({ //Remember, it's Vue, not vue
el: "#app",
  data() {
    return {
      myObject: {Field1: 'Value1', Field2: 'Value2'},
      myArray: ['Field1', 'Field2'],
      copyMyObject: {}, //solution 2
      copyMyObject1: {} //solution 3
    }
  },
  computed: {//solution 1
    computedObject: function(){
      return Object.assign({}, this.myObject)
    }
  },
  mounted: function(){ //solution 2
    this.copyMyObject= Object.assign({}, this.myObject)
    this.copyMyObject1= Object.assign({}, this.myObject)
  },
  watch: {//solution 2
    copyMyObject: function (newValue, oldValue){
      console.log('copyMyObject', newValue)
      //Custom actions can be performed here
    }
  },
  methods: {
    getObject: function () {//solution 1
      console.log('computedObject', this.computedObject)
      console.log('myObject', this.myObject)
    }
  }
})
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d4acaeadb9958aa0939eac3">[email protected]</a>/dist/vue.js"></script>
<div id="app">
  <button @click="getObject()">Click me!</button>
  <p>The downside: {{computedObject}}</p>
  <div v-for="property in myArray">
      <input type="text" v-model="computedObject[property]" />
  </div>
  <p>Original: {{myObject}}</p>
  <p>Clone: {{copyMyObject}}</p>
  <div v-for="property in myArray">
      <input type="text" v-model="copyMyObject[property]" />
  </div>
  <p>Clone: {{copyMyObject1}}</p>
  <div v-for="property in myArray">
      <input type="text" v-bind:value="copyMyObject1[property]" @input="copyMyObject1[property] = $event.target.value" />
  </div>
</div>

Answer №2

To create a new object based on the original one, you can do the following:

data: {
  updatedObject = Object.assign({}, myObject)
}

After creating the new object, you can incorporate it into your template like this:

<div v-for="property in myArray">
    <input type="text" v-model="updatedObject[property]" />
</div>

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

What is the method for stopping a slide in this script?

Welcome everyone! Check out this piece of code I have: <script type="text/javascript" > $(function(){ var time = 10000;//milliseconds var index = 0; var container = $("#containerr"); var child ...

Ways to remove the address bar from a mobile browser like Chrome or an Android browser

Is there a way to make videojs go full screen on Android devices when the URL is entered, without displaying the address bar? ...

Tips for extracting key values from an array of objects in Typescript

I am working with an array called studyTypes: const studyTypes = [ { value: "ENG", label: "ENG-RU", }, { value: "RU", label: "RU-ENG", }, ]; Additionally, I have a state variable set ...

Creating interactive popups using Web Map Service (WMS) with the

I am looking for a way to make a leaflet map loaded from a geoserver interactive by displaying popups with information. Can someone provide a solution using jsfiddle to help me understand? I am struggling to figure out how to achieve this. Essentially, I w ...

Selecting middleware to be executed based on Express JS request parameters

Can someone please advise me on how to select between two distinct middleware functions, based on the request for a specific endpoint? It may involve something along these lines: router.post("/findAvailableAgents", chooseMiddleware(middleware1, ...

Are tabs best displayed as an overlay?

I've been searching high and low for a tutorial on how to create an overlay with tabs similar to the Google Chrome webstore. If anyone knows of a tutorial or a combination of tutorials that can help me achieve this, please let me know! Link Any guida ...

Issue encountered while utilizing JQueryUI alongside TypeScript and the definition file from DefinitelyTyped

Currently, I'm attempting to incorporate JQueryUI with TypeScript by first installing JQueryUI using npm install jquery-ui-dist, and then installing JQuery with npm install jquery. Additionally, I have included the definition files from DefinitelyType ...

Standardize date formatting in AngularJS

Retrieve the date in the shared format: {{ dateValue | date:{{dateFormat}} }} The following service is provided: app.service('formatting', function() { var format = new Object(); format.dateFormat = 'medium' var ...

Tips for checking form input validity prior to opening a modelDialog

After successfully validating all required form fields, I am trying to open a modal dialog. Although I have managed to validate the form, I am struggling to write the code that will trigger the opening of the modal dialog upon successful validation. Do y ...

An object will not be returned unless the opening curly bracket is positioned directly next to the return statement

compClasses: function() { /* The functionality is different depending on the placement of curly brackets */ return { major: this.valA, minor: this.valB } /* It works like this, please pay attention to ...

expanding the expressjs res feature

I am currently working on implementing an error and notification feature for my expressjs app. My approach was to add a function by calling: app.use(function (req, res, next) { res.notice = function (msg) { res.send([Notice] ' + msg); } }); ...

When attempting to send data to the ServiceStack RESTful service, an error message of 'Access is denied' was received

I created a RESTful service using ServiceStack to send data to a database. It worked perfectly when tested locally. However, after deploying it to a server and running the same jQuery $.ajax call code, I encountered an 'Access is denied' error. I ...

"Error: Unable to locate module" encountered during the transition to Webpack 5

I am in the process of upgrading my React application to webpack version 5.72.0 (previously on 4.42.1). As part of this update, I have also upgraded webpack-cli to version 4.9.2, webpack-dev-server to version 4.8.1, and babel to version 7.17.9. However, I ...

Using jQuery, you can utilize the $.when() function with both a single deferred object and an

In my current jquery setup, I am working with two variables. trackFeatures - representing a single ajax request, and artistRequests - an array of ajax requests. I am looking for a way to create a condition that triggers when both trackFeatures and artist ...

Retrieve the overall number of job openings from the Github Job API

I have successfully created an Angular application that mirrors the functionality of However, I encountered a limitation where only 50 positions are available per page, To fetch additional jobs beyond the initial 50, I need to append "?page=X" to another ...

Encountering difficulties with integrating map controls into the Nuxt3/Vue3 mapbox feature for zooming

Recently, I started exploring Mapbox within my new Nuxt3 application. I managed to successfully render the map in my custom Map.vue component. However, I am facing trouble when trying to add controls and other options. Despite my efforts, I can't see ...

The 'Image' component does not have a propType defined for the native prop 'RCTImageView.overlayColor' with a native type of 'number'

Greetings, I am encountering an issue while attempting to run my react native application on Android. The app has been functioning flawlessly on iOS for several months, but this is our first endeavor at utilizing it on Android. We are using react-native .1 ...

Guide on automatically attaching a file to an input file type field from a database

Currently, I am implementing a PHP file attachment feature to upload files. Upon successful upload, the system stores the filename with its respective extension in the database. The issue arises when trying to retrieve and display all entries from the ...

Determining the quantity of displays

Can we detect the number of screens in use using JavaScript or jQuery? We are working on an application that should not be displayed on multiple screens, even if the hardware allows for it. Appreciate any assistance with this matter. Thank you. ...

Having trouble with Angular 2's Output/emit() function not functioning properly

Struggling to understand why I am unable to send or receive some data. The toggleNavigation() function is triggering, but unsure if the .emit() method is actually functioning as intended. My end goal is to collapse and expand the navigation menu, but for ...