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

Does moment/moment-timezone have a feature that allows for the conversion of a timezone name into a more easily comprehendible format?

Consider this example project where a timezone name needs to be converted to a more readable format. For instance: input: America/Los_Angeles output: America Los Angeles While "America/Los_Angeles" may seem human-readable, the requirement is to convert ...

"Combining Angular and jQuery for powerful web development

I am looking to develop an application using Angular and incorporate numerous jQuery animations and jQuery UI effects (such as animate, fadeIn, fadeOut, etc). Is it feasible to use jQuery functions in conjunction with Angular? ...

Saving table sorting in Redux with Ant Design Table

I am currently working with Antd Version 4.2.2 in my ReactJS project. Specifically, I am utilizing the Ant Design < Table /> component. My goal is to save the sorting order that is applied to the columns into Redux state. Here is my current approa ...

Tips for identifying the clicked location inside an element using JavaScript?

Is there a way in JavaScript to find out the exact position of a click within an element, like its distance from the left, right, or center? I'm struggling to determine whether the clicked area is on the left, center, or right side. https://i.stack.i ...

Is there a way for me to determine the total number of seconds since the chatbot was first opened?

Here is a snippet of my HTML code: <div class="chatbot chatbot--closed "> <div class="chatbot__header"> <p><strong>Got a question?</strong> <span class="u-text-highlight">Ask Harry</span></p> <s ...

Make sure the "Treat labels as text" option is set to true when creating a chart in a Google spreadsheet using a script

I am currently working on a script using Google Spreadsheet Apps Script interface and I need to set the marker for 'Treat labels as text' to true. Despite searching through App Script documentation, I couldn't find any specific mention of t ...

Retrieve information from the existing URL and utilize it as a parameter in an ajax request

Currently, I am working on a website with only one HTML page. The main functionality involves fetching the URL to extract an ID and then sending it to an API using an AJAX call. Upon success, the data related to the extracted ID is displayed on the page. H ...

Exploring the perfect blend of ReactJs Router Links with material-ui components, such as buttons

I am currently facing a challenge in integrating the functionality of react router with material ui components. For example, I have a scenario where I want to combine a router and a button. I attempted to merge them together and customize their style. In ...

Keep the music playing by turning the page and using Amplitude.js to continue the song

I have implemented Amplitude.js to play dynamic songs using a server-side php script. My objective is to determine if a song is currently playing, and if so, before navigating away from the page, save the song's index and current position (in percenta ...

When Highcharts and AngularJS team up, beware of the memory leak!

I've integrated highcharts into my AngularJS application using the highcharts-ng directive, but I'm encountering a persistent memory leak issue. My app is a slideshow with rotating slides that include charts. To investigate further, I created 3 ...

What is the most effective way in MongoDB to insert data only if it does not already exist in the database?

Is there an optimal way to insert data into MongoDB only if it doesn't already exist in the table? The unique field for searching is hash, which is also indexed. router.post('/', async (req, res) => { try{ var id = null const ...

Trigger the execution of a Python script through a webpage with just the click of a button

I have a small web interface where I need to control a Python script that is constantly gathering data from a sensor in a while loop. Ideally, I would like the ability to start and stop this script with the click of a button. While stopping the script is s ...

Three.js functions smoothly on both Android devices and desktop computers using Chrome, unfortunately it is not compatible with Safari

After diving into learning three.js, I decided to incorporate it into my angular 11 project. I created a simple demo using a SphereBufferGeometry and deployed it on github pages. Surprisingly, when I accessed it on an android phone, everything worked perfe ...

transfer a product attribute value to a different product attribute within the Magento platform

There is an attribute called Weight : Attribute Code: weight Scope: general Catalog Input Type for Store Owner: Text Field Values Required: yes Apply To: Simple Product, Bundle Product Allow HTML Tags on Frontend: yes Also, there is a General Weight attr ...

Tips on retrieving a value nested within 3 layers in Angular

In my Angular application, I have three components - A, B, and C. Component A serves as the main component, Component B is a smaller section nested inside A, and Component C represents a modal dialog. The template code for Component A looks something like ...

Transform a span into a div while retaining its content and styles, ensuring compatibility with Internet Explorer

Is there a reliable JavaScript method to convert a span into a div while preserving its contents and the original classes of the span? The classes are pre-set, so hardcoding should be possible. <span class="my class"> <p class="conten ...

Error message: "Unable to locate command after successful installation of @vue/cli

I recently installed @vue/cli using npm with the command npm install -g @vue/cli. However, when I attempt to use the vue command, it returns -bash: vue: command not found. To troubleshoot this, I added export PATH="/usr/local/Cellar/node/11.2.0/lib/node_mo ...

What is the process for importing module functions in Svelte when utilizing npm?

I'm having trouble understanding how to properly use imports in Svelte with npm. I have a Svelte component that I can't seem to get working. Uncommenting "//import { Configuration, OpenAIApi } from "openai";" leads to the error message: [!] (plug ...

What is the best way to determine the index of an element within an array when using the C

#define ID_A 5 #define ID_B 7 #define ID_C 9 const int id_arr={ ID_A, ID_B, ID_C, }; If I want to find out the offset of ID_C in id_arr without running the code, is there a way to achieve this using macros or any other method? ...

Filtering MUI Data Grid by array elements

I am in the process of developing a management system that utilizes three MUIDataGrids. Although only one grid is displayed at a time, users can switch between the three grids by clicking on tabs located above. The setup I have resembles the Facebook Ads ...