Troubles encountered when populating the array within a Vue component

I am experiencing an issue with my ProductCard component where the addItem method is not successfully adding a new item to the array.

<template>
  <div class="card">
    <div v-for="item in TodoItems" :key="item.id">
      <TodoItem :item="item"></TodoItem>
    </div>
    <form>
      <input type="text" v-model="newItemText">
      <button type="submit" v-on:click="addItem">Submit</button>
    </form>
  </div>
</template>

<script async>
import TodoItem from "@/components/TodoItem.vue";

export default {
  name: "ProductCard",
  components: {TodoItem},
  data(){
    return{
      TodoItems: [],
      newItemText: '',
    }
  },

  methods: {
    addItem() {
      const newItem = {
        id: this.TodoItems.length,
        text: this.newItemText,
        completed: false
      }
      this.TodoItems.push(newItem);

      console.log('Successfully added item');
      console.log(this.TodoItems.length);

      this.newItemText = '';

    },
  }
}
</script>

Answer №1

When a user clicks on a button with type="submit" within a form (or simply presses Enter when a form field is selected), the form gets submitted and the page reloads. This results in not being able to see the added elements as the page refreshes after each addition.

To prevent this behavior, here are some methods:

The First method - Add ".prevent" modifier to the "v-on:click" directive

<form>
  <input type="text" v-model="newItemText">
  <button type="submit" v-on:click.prevent="addItem">Submit</button>
</form>

This allows adding an item by clicking on the "Submit" button or pressing the Enter key.

The Second method - Handle the submit event with ".prevent" modifier in the form element and remove the "v-on:click" directive from the button element. Ensure that the button has a type="submit".

<form @submit.prevent="addItem">
  <input type="text" v-model="newItemText">
  <button type="submit">Submit</button>
</form>

This method also allows adding an item by clicking on the "Submit" button or hitting Enter.

The Third method - Change the button type to "button" AND handle the form's submit event with ".prevent" modifier (if you don't handle this event, the page will reload when you press Enter).

<form @submit.prevent>
  <input type="text" v-model="newItemText">
  <button type="button" v-on:click="addItem">Submit</button>
</form>

This method works too but only when the user clicks on the Submit button. The Enter key won't function in this case.

I recommend opting for the first or second method.

Just so you know: ".prevent" modifier is essentially a shorthand for event.preventDefault();

You can view the complete code and test it out here - https://codepen.io/AlekseiKrivo/pen/BaqwMQo

For more information, visit - https://vuejs.org/guide/essentials/event-handling.html#event-modifiers

Learn about preventDefault here - https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault

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 causes the scrollbar to not extend to the bottom when connected to another scrollbar via a JavaScript equation?

I have been working on a code that involves multiple scrollbars that are all linked together. When you move one scrollbar, the other two will move proportionally. However, due to differences in width, the scroller doesn't always reach the end of the s ...

Ending an $.ajax request when the page is exited

Currently, I have a function set on a timer to retrieve data in the background: (function fetchSubPage() { setTimeout(function() { if (count++ < pagelist.length) { loadSubPage(pagelist[count]); fetchSubPage(); ...

The success callback in the first call will only be triggered when a breakpoint is established

I currently have an ASP.NET MVC webpage with Bootstrap and several plugins integrated. I am attempting to implement a confirmation message using the Bootbox plugin before deleting a record, followed by reloading the page upon successful deletion. Everythi ...

The method for retrieving values and $id from a $firebaseArray using angularJS

Hey there, I'm fairly new to working with Firebase and I seem to be stuck on a problem that I can't find a solution for despite looking in many different places. Here is the structure of my Firebase database: I am trying to retrieve data from a s ...

Files with extensions containing wildcards will trigger a 404 error when accessed from the public folder in NextJS

I have successfully set up my public folder to serve static files, however I am encountering an issue with files that have a leading dot in their filename (.**). Specifically, I need to host the "well-known" text file for apple-pay domain verification, wh ...

Encountered an error while running npm run dev on a NextJS application due to an

Upon running the npm run dev command, the next app is displaying an error message: $→mmoLD;%g?wŷ↓▬ovH0a5*ؒl͛Siy☺rO7%L]%∟hk ^ SyntaxError: Invalid or unexpected token at wrapSafe (internal/modules/cjs/loader.js:988:16) at Module._comp ...

Can a props be retrieved and passed as an argument to a function?

My goal is to retrieve a prop from MapsStateToProps using react-redux's connect and then pass it to a child component. This prop serves as an argument for a function, which in turn returns something that becomes the state of the child component. Alth ...

Vue component triggering updates in another component inexplicably

I'm stuck in a never-ending loop here, so I am desperately seeking some guidance. My setup is quite simple and I have managed to replicate it in a Fiddle. It includes 3 components: A main form A radio button selection A panel containing the radio but ...

The React getTime() method does not properly update the state

I am attempting to update the state of the component Demoss using an external function called getTime(). My goal is to start updating the time in the state time when the page loads. In order to achieve this, I have called it in the componentDidMount meth ...

Is it possible to pass a variable to a text constant in Angular?

In my constant file, I keep track of all global values. Here is the content of the file: module.exports = { PORT: process.env.PORT || 4000, SERVER: "http://localhost:4200", FAIL_RESULT: "NOK", SUCCESSFUL_RESULT: "OK ...

JavaScript AJAX function is returning an undefined value rather than a boolean true or false

My AJAX call function in jQuery has a complete section with the following code: complete: function(XMLHttpRequest, textStatus) { if(textStatus == "success") { return(true); } else { return(false); } } However, when ...

An unusual occurrence with the setTimeOut function within a for loop was observed

When attempting to log numbers at specific intervals on the console, I encountered an unexpected issue. Instead of logging each number after a set interval, all numbers are logged out simultaneously. I've experimented with two different approaches to ...

Unending cycle occurs when utilizing a computed property alongside Vue Chart js

My goal is to refresh my chart with new data from an API call every 5 seconds. However, the chart is updating excessively, rendering each point hundreds of times. After checking the logs, I discovered that there seems to be an infinite loop causing this is ...

Elevate the element from the choice API to the organization API using this.$parent

I recently developed a Vue 3 component called "Tab" using the option API. Here is the code: export default { name: "Tab", props: { name: {required: true}, iconClass: {required: true}, selected: {default: false} }, da ...

Guide to uploading a recorded audio file (Blob) to a server using ReactJS

I'm having trouble using the react-media-recorder library to send recorded voice as a file to my backend. The backend only supports mp3 and ogg formats. Can anyone provide guidance on how to accomplish this task? Your help would be greatly appreciated ...

Utilizing a switch statement for form validation

Currently, I am in the process of creating a form validation that involves two conditions for validation. I'm considering using a combination of switch case and if else statements. Would this be an appropriate approach or is it generally discouraged? ...

Is there a way for me to adjust the image dimensions so that it doesn't surpass the width of its parent container?

When working with images, it can be tricky to set the original width while also ensuring it fits within a parent container. For example, if the parent container has a width of 1000px, you may want the image to have a max-width of 100%, but not exceed 1000p ...

Prompting Javascript Alert prior to redirection in ASP.NET

My current code is set up to display a message in an update panel while updating: string jv = "alert('Time OutAlert');"; ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", jv, true); It's working well in displaying the me ...

Multiple requests are being sent via AJAX

Despite numerous other posts addressing the same issue, I have not been able to find a solution for my problem. The AJAX request appears to be sent multiple times. var checkAllStatus = function () { $.ajax({ cache: false, type: "POST", ...

How can Node.js improve callback functions and integrate nodemailer for optimal performance?

I'm currently working on a new feature that involves sending a post request to download HTML pages from specific URLs, zip them, and then email the zipped file to a designated email address. The endpoint for this route looks like http://localhost:3000 ...