skip to Main Content

In my ProductCard component I need to be able to create a new item with the addItem method, it does not seem to load the item in 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",
  //hierin defineren we globale variabelen
  components: {TodoItem},
  //in data moeten we altijd iets returnen
  data(){
    return{
      //hierin defineren we alle variabelen die we binnen ons component lokaal gaan gebruiken

      TodoItems: [],
      newItemText: '',
    }
  },

  methods: {
    addItem() {
      // create a new item object and push it to the array
      const newItem = {
        id: this.TodoItems.length,
        text: this.newItemText,
        completed: false
      }
      this.TodoItems.push(newItem);

      console.log('zit er in');
      console.log(this.TodoItems.length);

      // clear the input field
      this.newItemText = '';


    },
  }
}
</script>

2

Answers


  1. By default when user clicks to a button with type="submit" inside a form – a form will be submitted and a page will be reloaded. This is why you don’t see added elements, the page reloads after every adding.

    To prevent this behavior you should use v-on:click with a "prevent" modifier

    Just change:

    v-on:click="addItem"
    

    to

    v-on:click.prevent="addItem"
    

    .prevent modifier is just a syntactic sugar for event.preventDefault();

    You can read about this more here – https://vuejs.org/guide/essentials/event-handling.html#event-modifiers

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

    Login or Signup to reply.
  2. One more solution for this:

    Handle a submit event with .prevent modifier in a form element and remove "v-on:click" directive from the button element.

    It also allows you add an item by hitting enter

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

    You can try it here – https://codepen.io/AlekseiKrivo/pen/BaqwMQo

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search