Ad

V-model Not Working With Javascript Functions

- 1 answer

I am new to Vue JS and have been learning it from the documentation provided. My project is a simple task adding web-app. On using the v-model directive, I'm not getting any output. My javascript function to add the task is apparently not being called.

<template>
  <div id="text">
       TASKS:
      <form onsubmit="return addTodo()">
        <input type="text" class="todo-input" placeholder="What's up" v-model="message">
        <input type="date" class="todo-input" v-model="ddate" >
        <input type="submit" value="Add">
      </form>
<div v-for="(todo, index) in todos" :key="todo.id" class="todo-item">
          <div>
              {{todo.id}}{{todo.title}}{{todo.date}}
            </div>
          </div>
     </div>
  </div>
</template>
export default {
  name: 'todo-list', 
  data () { 
    return {
      message: '',
      ddate: '',
      idForTodo: 1,
      todos: [
          
      ]
    }
  },
  methods: {
      addTodo(){
        if(this.message.trim().length == 0){
          return
        }
          this.todos.push({
              id: this.idForTodo,
              title: this.message,
              completed: false,
              editing: false,
              date: this.ddate,
          })
          this.ddate = ''
          this.message = ''
          this.idForTodo++
      },
      
  }
}
Ad

Answer

Looks like someone edited the question with correct code while I was writing the answer. I tried and tested same code in code snippet and it's working.

const app = new Vue({
  el: '#text',
  data() {
    return {
      message: '',
      ddate: '',
      idForTodo: 1,
      todos: [
          
      ]
    }
  },
    methods: {
      addTodo(){
        console.log(this.message)
        if(this.message.trim().length == 0){
          return
        }
        this.todos.push({
          id: this.idForTodo,
          title: this.message,
          completed: false,
          editing: false,
          date: this.ddate,
        })
        this.ddate = ''
        this.message = ''
        this.idForTodo++
      }   
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.0/vue.js"></script>

<div id="text">
  TASKS:
  <form>
    <input type="text" class="todo-input" placeholder="What's up" v-model="message">
    <input type="date" class="todo-input" v-model="ddate" >
    <button v-on:click.prevent="addTodo">Add</button>
  </form>
  <div v-for="(todo, index) in todos" :key="todo.id" class="todo-item">
    <div>
      {{todo.id}} {{todo.title}} {{todo.date}}
    </div>
  </div>
</div>

Ad
source: stackoverflow.com
Ad