Home > Software engineering >  v-model not working with javascript functions
v-model not working with javascript functions

Time:02-16

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"  placeholder="What's up" v-model="message">
        <input type="date"  v-model="ddate" >
        <input type="submit" value="Add">
      </form>
<div v-for="(todo, index) in todos" :key="todo.id" >
          <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  
      },
      
  }
}

CodePudding user response:

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

CodePudding user response:

If you are storing a value from a set of radio. buttons in a property, you need to identify the buttons. Not with the id, but with a value. Try this:

{{data.variant}}
  • Related