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 could be causing the repetition of the same cookie in my request header when using jQuery ajax?

Stuck in a dilemma for hours now, seeking assistance or suggestions from anyone who can help me out. To sum it up, I have an asp.net web api application where I am trying to fetch data from a web api and populate multiple dropdown lists on a page using jQ ...

What is the reason behind Firefox failing to display a linear gradient when the background-size values are more than 255px?

I am working on creating a grid overlay using an absolutely positioned non-interactive div. My approach involves using the repeating-linear-gradient property as suggested by others for this purpose. The functionality works smoothly in Chrome, but I seem to ...

Troubleshooting issue with node.js 13 import functionality

$ node --version v13.8.0 We will now proceed to create three files: // package.json { "type": "module" } // foobar.js function foo() { console.log('foo') } export default {foo} // index.js import Foo from './foobar ...

Error message: The import from './components/headerComponent/header' failed because it does not have a default export. Make sure to export it as default to be able to import it

I've been trying to bring a header from one file into another, but it's not cooperating. import React from 'react'; import { Typography, Card, CardContent } from '@material-ui/core'; import Header from './components/head ...

Guide on creating rsa key pair on the client side with angular2

Is there a way to generate an 'rsa' key-pair on the client-side using angular2? I am looking to create a private/public key pair and store the private key in a database while using the public key on the client side. How can this be achieved? I c ...

Alter the content of a div depending on the values of three different elements

Hello everyone, I am new to the world of jQuery and javascript, and I am facing a challenge that I need some help with. Within a form, there are two fields that I would like to perform calculations on. Here is what I have attempted so far: jQuery.fn.calcu ...

The server returned a response that was void of any content

I have encountered an issue while trying to retrieve data from my server. The request works perfectly fine when tested with Postman, returning the expected data. However, upon implementing the request in my application, I receive an empty object with prope ...

What is the best method for iterating through a table's td tags in Laravel and Vue.js?

In the data below, I am attempting to loop through each Item in the table within the <td> tag so that two items are displayed in a single column. user >"name":"Bob" >"id":1 >"Item": >"name":"Desk" >"name":" ...

"Wordpress Pluto theme: A stellar choice for your

I'm trying to add a link in my main template.index file that will redirect to one of my pages when clicked on the JavaScript button at the top in Pluto theme. Currently, the text is there but clicking on it opens something I don't want. Here&apo ...

Is there a way to verify if a button is disabled with Vue Test Utils?

I'm currently facing an issue while testing a Vue component regarding the disabled state of a button. How can I retrieve and verify a button's disabled status during my tests? So far, I have attempted to use .attributes(), but it seems that this ...

jQuery does not have the capability to add or remove classes

I am currently using Vue.js within Laravel, and in the watch action, I am utilizing jQuery. I am puzzled as to why hasClass is functioning correctly, but addClass, removeClass, and toggleClass are not working as expected. Here is a snippet of my HTML cod ...

AngularJs input field with a dynamic ng-model for real-time data binding

Currently facing an issue with my static template on the render page. <form name="AddArticle" ng-submit="addArticle()" class="form add-article"> <input type="text" value="first" init-from-form ng-model="article.text[0]" /> <input typ ...

What causes duplicate packages to appear in Bower at times?

There appears to be two identical packages available for the Sugar javascript library, sugar and sugarjs. Are these packages interchangeable or are they being maintained separately by different individuals? ➔ bower info sugarjs bower sugarjs#* ...

Is it not possible to utilize v-for on the root element of a stateful component due to rendering multiple elements?

app.js var UserList = { template: ` <tr v-for="user in UsersData"> <th>{{ user.idx }}</th> <td>{{ user.id }}</td> </tr> `, data: function () { return { ...

What is the method to determine if a date is larger or smaller than another using Javascript?

Using the inputText function retrieves the value entered in the textbox, while the hidden field value returns the current value. This is my current code snippet: if (inputText.value.length != 0) { if (inputText.value < document.getElementById(&apo ...

Implementing a codeigniter delete confirmation box with Javascript

I have tried numerous solutions on this site, but nothing seems to be working for me. I am trying to implement a pop-up window confirmation before deleting my data. Here is the code I am using: <a href="<?php echo site_url('admin/barang/delet ...

When an element is appended, its image height may sometimes be mistakenly reported as

I am dynamically adding divs and I need to retrieve the height and width of an image. Based on this information, I have to apply CSS to the MB-Container class. For example: if the image is portrait orientation, set container width to 100%. If it's ...

use dotenv in your Build Folder

Is it possible to have my .env file in my React JS project move to the build folder when I run NPM build command? If so, how can this be achieved? If not, what would be the alternative solution? I attempted using "build": "cp .env.template ...

Utilize external URL in trigger.io's custom UIWebView component

I'm in the process of transitioning my existing backbone application, designed for a native iOS UIWebView, over to trigger.io in order to utilize its image caching and camera access features. The goal is to make this migration quickly and efficiently. ...

Error: Unable to locate module: "./library". The parent module directory is "/"

I keep encountering an issue in my project when attempting to load a module. Whenever I try to import it from the node_modules folder, I receive the following error: Uncaught Error: Module not found: "./MyLibrary". Parent module folder was: "/" However, i ...