Clear v-model without changing its associated values

I'm facing an issue with my <input> fields, which look like this:

<input type="text" v-model=user.name" />
<input type="text" v-model="user.phone" />
<button @click="add">add user</button>

Whenever the add user button is clicked, it should add the current user to the users array and clear the v-model values (to allow for adding more users). This is how my add() method is implemented:

add()
{
  this.users.push( this.user );
  this.user.name = '';
  this.user.phone = '';
}

The problem I'm encountering is that after resetting the v-model values of the user, the element in the users array also gets reset to an empty string. How can I reset the v-model without affecting the data in the users array?

Answer №1

The easiest method is to completely reset the entire user object instead of modifying it property by property:

add()
{
  this.users.push(this.user);
  this.user = {name: '', phone: ''};
}

Check out the demonstration below:

new Vue({
  el: '#app',
  data: {
    user: {name: '', phone: ''},
    users: []
  },
  methods: {
    add() {
      this.users.push(this.user);
      this.user = {name: '', phone: ''};
    }
  }
})
<script src="https://unpkg.com/vue"></script>

<div id="app">
  name: <input type="text" v-model="user.name" /><br>
  phone: <input type="text" v-model="user.phone" /><br>
  <button @click="add">add user</button>
  <hr>
  users: {{ users }}
</div>

Why did it not work as expected?

When you use:

this.users.push( this.user );
// You are changing the name inside the users array
this.user.name = '';

By pushing this.user into the this.users array, any subsequent changes will affect the same object that is now in the array.

In contrast, by overwriting it, a new object is created:

this.users.push(this.user);
this.user = {name: '', phone: ''};
// The above line points `this.user` to a new object.
// Changes made to `this.user` after this point do not affect the previous object inside the array
// For example:
this.user.name = 'bob';

Alternative Approach: Cloning.

If you prefer cloning, there are a few options available. Starting with "manual" cloning:

new Vue({
  el: '#app',
  data: {
    user: {name: '', phone: ''},
    users: []
  },
  methods: {
    add() {
      this.users.push({name: this.user.name, phone: this.user.phone});
      this.user.name = '';
      this.user.phone = '';
    }
  }
})
<script src="https://unpkg.com/vue"></script>

<div id="app">
  name: <input type="text" v-model="user.name" /><br>
  phone: <input type="text" v-model="user.phone" /><br>
  <button @click="add">add user</button>
  <hr>
  users: {{ users }}
</div>

For deep cloning:

new Vue({
  el: '#app',
  data: {
    user: {name: '', phone: ''},
    users: []
  },
  methods: {
    add() {
      let userDeepClone = JSON.parse(JSON.stringify(this.user));
      this.users.push(userDeepClone);
      this.user.name = '';
      this.user.phone = '';
    }
  }
})
<script src="https://unpkg.com/vue"></script>

<div id="app">
  name: <input type="text" v-model="user.name" /><br>
  phone: <input type="text" v-model="user.phone" /><br>
  <button @click="add">add user</button>
  <hr>
  users: {{ users }}
</div>

Lastly, for shallow cloning:

new Vue({
  el: '#app',
  data: {
    user: {name: '', phone: ''},
    users: []
  },
  methods: {
    add() {
      let userShallowClone = {...this.user}; // or Object.assign({}, this.user);
      this.users.push(userShallowClone);
      this.user.name = '';
      this.user.phone = '';
    }
  }
})
<script src="https://unpkg.com/vue"></script>

<div id="app">
  name: <input type="text" v-model="user.name" /><br>
  phone: <input type="text" v-model="user.phone" /><br>
  <button @click="add">add user</button>
  <hr>
  users: {{ users }}
</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

use javascript or jquery to conceal the textbox control

Looking to conceal a textbox control using javascript or jquery. I attempted the following code: document.getElementsByName('Custom_Field_Custom1').style.display="none"; Unfortunately, I received an error in the java console: document.getEle ...

Sending data to Layout for customizable routes (App Router) in Next.js version 13

Looking to pass props to the Layout component for dynamic routes in my project structure: /app -/(site) --/layout.tsx --/page.tsx --/[slug]/page.tsx --/[slug]/layout.tsx In the site layout: export default async function IndexRoute({ children }: { chil ...

What steps can I take to ensure that my React child components will render successfully, even if a prop is absent

TLDR; Seeking solution to render child components in React even if a property of this.props is missing. My React app utilizes Yahoo's Fluxible and fetches data from a Wordpress site using WP REST API. Sometimes, the API may return incomplete data cau ...

Link to download an Excel spreadsheet

My server is capable of generating excel files dynamically, and I am utilizing AJAX to download these dynamic excel files. Upon successful completion in the callback function, I receive the data for the excel file. $.ajax({ url: exporting. ...

The Vue component fails to display the updated data even after the prop data has been modified

This is the parent component called abc.vue <v-card outlined class="mt-4"> <DetailsTable v-show="toggleClientData" :columnDefs="columnDefs" :rowData="rowData" /> </v-card> methods:{ aggridData() { let self = this; th ...

What is the reason behind the necessity of using setTimeout with a delay of at least 50ms for JS .focus()

Problem While creating a page for a client at work, I encountered an issue with a slide-out search bar. When clicking the button to open the search input field (which starts off hidden), I want the focus to shift to that input field. Oddly, I found that ...

Having trouble with JavaScript's XMLHttpRequest returning an 'undefined' string on the first run of my script. I need to find a way to ensure that it loads correctly during

Before we dive in, a quick disclaimer: My knowledge of JS is limited, and I typically learn on the go when creating scripts. However, my usual method didn't work this time. Currently, I'm working on a small JS script that will function as a book ...

Troubleshooting the Node.js Server Error Encountered when Enabling AngularJS html5Mode(true)

When using routeProvider and stateProvider in AngularJS with HTML5 mode set to true, everything functions correctly until the page is refreshed. On a Node.js server, I am unsure of what needs to be written on the server side to prevent receiving a "Can no ...

Unbounded AngularJS 1.x looping of Ag-grid's server-side row model for retrieving infinite rows

I am obtaining a set of rows from the server, along with the lastRowIndex (which is currently at -1, indicating that there are more records available than what is being displayed). The column definition has been created and I can see the column headers in ...

What is the best way to ensure a cron job executing a Node.js script can access variables stored in an .env file?

Currently, I have a scheduled job using cron that runs a Node.js script. This script utilizes the dotenv package to access API keys stored in a .env file. Running the Node.js script from the command line retrieves the variables from the .env file successf ...

Create dynamic transitions for hidden elements using a special technique

Is it possible to smoothly transition a div element from display:none to display:block? I attempted to first set the display to block and then apply a transition, but it doesn't seem to be working as expected. HTML <input type="text" class="inp"& ...

Encountered an issue while attempting to decode the downloaded font. Parsing error from OTS in Vue

I'm facing an issue with importing a web-font into a specific component in my Vue App (built using the Vue cli webpack template). In one of my components, I attempted to import the fonts by referencing a _fonts.scss file within the project that looks ...

Utilizing Next.js with formidable for efficient parsing of multipart/form-data

I've been working on developing a next.js application that is supposed to handle multipart/form-data and then process it to extract the name, address, and file data from an endpoint. Although I attempted to use Formidable library for parsing the form ...

The use of Google Material Symbols is incompatible with lazy loaded components in a Vue.js application

How can I implement material symbols in a lazy loaded or dynamically imported Vue.js component? My current configuration is not working as the icons only show up in statically loaded views: Main.js import { createApp } from 'vue/dist/vue.esm-bundler& ...

Node.js - Locate a specific parameter within an array that is nested within a JSON object, and retrieve the remaining

I am working with a Node.js API call that returns a JSON object. My goal is to extract the customer's phone number from this object using a specific function, like body.result.reservations[X of reserv.].client.phone, and retrieve parameters such as p ...

Capture data from a Telegram bot and store it in a Google Sheet

I am trying to use a spreadsheet through a Telegram bot as a TODO list so that when I input something on my phone, it is saved in the spreadsheet. (I'm following this tutorial https://www.youtube.com/watch?v=XoTpdxbkGGk, which seems accurate with Goog ...

The Angular Material md-input-container consumes a significant amount of space

Currently, I am exploring a sample in Angular Material. It appears that the md-input-container tag is taking up a substantial amount of space by default. The output is shown below: However, I have come across the md-input-content tag, which occupies less ...

Utilizing JSON Data for Dynamically Displaying Database Objects on a Google Map

After carefully reviewing the information provided in the initial responses and working on implementation, I am updating this question. I am currently utilizing the Google Maps API to incorporate a map into my Ruby on Rails website. Within my markets mode ...

Animations of bezier curves created with Three.js

UPDATED: SOLUTION FOUND I am in need of guidance on how to create animation for the movement of points along a curve to simulate string motion in 3D while keeping performance in mind. Imagine multiple strings between two points, for example. Check out t ...

Error encountered in thread "main": Issue with parsing string literal

import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class FindElementsUsingJS { static WebDriver driver= new FirefoxDriver(); public static void main(Stri ...