Tips for managing input for objects in Vue when the object hasn't been declared yet?

<input type="text" v-model="object[obj]">

Output:

object:{'obj1':value}

Desired outcome after input is added:

object:{'obj1':{'prop1':value,'prop2':value}} 
<input type="text" v-model="obj">

<input type="text" v-model="object[obj]['prop1']">
<input type="text" v-model="object[obj]['prop2']">
{{object}}
export default {
  data() {
    return {
      obj: '',
      object: {},
    }
  }
}

Is it possible to accomplish this using v-model or a custom input handler?

Answer №1

If you want to dynamically create object keys in Vue, you can set up a change-event handler on the input element using vm.$set():

<template>
  <div>
    <input v-model="obj" @change="onKeyChange">
  </div>
</template>

<script>
export default {
  methods: {
    onKeyChange() {
      const key = this.obj && this.obj.trim()
      if (key) {
        this.$set(this.object, key, { prop1: '', prop2: '' })
      }
    }
  }
}
</script>

To handle rendering of inputs that depend on object[obj], use conditional rendering with v-if to avoid errors when accessing prop1/prop2 on undefined objects:

<template>
  <div>
    <template v-if="object[obj]">
      <input v-model="object[obj]['prop1']">
      <input v-model="object[obj]['prop2']">
    </template>
  </div>
</template>

Check out the working demo for reference.

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

Using JavaScript to interact with elements inside an iframe on a webpage

In a simple scenario, I am experiencing incorrect results. Code snippet from MyFrame.HTML: <!DOCTYPE html> <html> <head> <title>My Frame</title> </head> <body> <a href="https://www.google.com& ...

The HTML Canvas seems to be malfunctioning for some unknown reason

As a beginner in programming, I am struggling to understand why the code below is not working. The first three lines of the script are necessary for another part of the webpage, but I don't see how that would affect the rest of the code: <!DOCTY ...

When the button/link is clicked, I must dynamically create a modal popup that includes a user control

I am currently working on improving an asp.net web forms website by incorporating popup modals to display the rental rates for available equipment. The challenge arises when dealing with pages where each piece of equipment has different rates, requiring a ...

Is it considered secure to encase a function within jQuery's removeClass()?

I'm currently developing a unique slider that includes a dynamic video element. With each slide transition, a new video is added to the DOM while the previous one is removed. To achieve this effect, I am utilizing CSS transitions along with a specific ...

How can you modify the starting point of data in jQuery flot?

Currently using Flot to create a graph displaying clicks per minute within the first 60 minutes of short URLs generated at . The graph currently displays data from minute 0 to minute 59. My query is about adjusting the data to start at 1 and end at 59, wh ...

How can I automatically scroll to an anchor element once CSS animation has finished

I am currently working on a CSS animation that looks like this: @-webkit-keyframes flip { 0% {opacity:1;} 100% {opacity: 0;} //This could be 90% //And here could be frame for 100% which would scroll it down. } #headercover { -webkit-animation-name ...

using http to handle a 404 error

This specific function is designed to fetch data under normal circumstances and to return a value of 0 in the event of a 404 error. function retrieveData(url) { if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); ...

What steps can be taken to resolve the error message: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data?

I'm facing an issue while trying to retrieve data for my map using an AJAX call. The error message I receive is: SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data. Interestingly, two previous datasets in my applicatio ...

Responding with a 404 Error in Node.js and Express with Callbacks

Apologies for the lackluster title, I couldn't come up with anything better. Let's delve into the following code snippet: app.use(function(request, response){ request.addListener('end', function() { parseUrl(request.url, fu ...

Node.js Axios Returns Bad Request with Status Code 400

I am currently facing an issue while trying to send the results of a nodejs query to an endpoint. Interestingly, I receive a successful response when using Postman with the correct parameters, but encounter errors when attempting to use axios. data: ' ...

The returned state from setState(prev) seems to be in the opposite order when referencing another useState variable within a useEffect

As part of my interactive chat simulation project, I have implemented a feature where users can click on a button named obj4 to start their chat session. Initially, everything functions smoothly, displaying messages 1-4 in the correct order. However, when ...

Issue with Jquery similar to javascript createElement

I am attempting to replicate the code below using jQuery: var newElem = document.createElement("div"); newElem.innerHTML = "DynaColumn"; newElem.className = "ui-state-default ui-corner-all"; return newElem; This is the jQ ...

Can ChatGPT Service Error be resolved?

I tried using chatGPT to help me with my HTML code, but every time I opened it I received an error message saying "Failed to get service" Here is the code that I want to make work: <html> <head></head> <body> <script& ...

Challenges arise when transferring data retrieved from a table into a bootstrap modal window

I have been attempting to transfer values from a table into a modal. Initially, I successfully displayed the <td> values in an alert when a button was clicked on a specific row. Now, I am aiming to take it a step further by having these <td> va ...

Utilizing Javascript to load a vast amount of data onto the browser, followed by initiating an XML

Looking for a solution to send XML requests containing values and content from files obtained by filling out an HTML form. With 5 large files, some exceeding 70 MB, I have implemented JavaScript functions to load file contents and assemble the XML request. ...

Struggling with TypeScript declaration files has been a challenge for me

I'm encountering an issue with using the trace function in my TypeScript code. The function has been declared in a .d.ts file as shown below: declare function trace(arg: string | number | boolean); declare function trace(arg: { id: number; name: strin ...

Implement a feature that adds a circle element when an image is clicked in a React application

I am attempting to create a program that allows users to add circles to an image by clicking on it. Essentially, when the user clicks at coordinates (x,y), a circle with a radius of 10 will appear at that location. I am exploring ways to implement meta-pro ...

Solution to trigger CSS :hover to refresh following a transition (such as expanding a menu)

While there are existing discussions on this topic, I am presenting my query for two specific reasons: It introduces a potential alternative solution The demo code could be helpful to individuals looking to emulate a menu Following a CSS transition, the ...

How to resolve CORS error when using custom request header in Django with JavaScript and redirecting to OPTIONS request?

I am currently working on building an API library using Django. This API will be accessed by javascript, with the Django-API and javascript running on separate servers. The Django API library requires a custom request header from the javascript front end, ...

Tips for creating a dynamic system to continuously add more HTML tables in PHP

I am working with an HTML table where the data is retrieved from a database. I need to add new rows to enter additional data, but the numbering does not continue from the last number. My question is how can I increase the numbering in the table. Please ref ...