1

我正在尝试将输入的值作为 a 添加<li><ul>列表中。

我可以通过将值绑定到 lis 的数组列表来添加它。但是,当我清理输入字段时,它不会留在那里。我怎样才能解决这个问题?

HTML 代码:

<div id="app">
  <h1>{{ message }}</h1>
  <form v-on:submit.prevent="addNewTodo">
    <input type="text" v-model="todo.task">
    <button type="submit">Add todo</button>
  </form>

  <ul>
    <li v-for="todo in todos" :class="{ completed: todo.isActive }" @click="$set(todo, 'isActive', !todo.isActive)">
     {{ todo.task }} <span v-on:click="deleteTodo">{{ todo.delete }}</span>
    </li>
  </ul>
</div>

JS代码:

var app = new Vue({
  el: '#app',
  data: {
    message: 'List of things to do today',
    todos: [
      { task: 'Have breakfast', delete:'(x)'},
      { task: 'Go to the gym', delete:'(x)'},
      { task: 'Study Vuejs', delete:'(x)'}
    ],
    todo: {task: '', delete: '(x)'}
  },
  methods: {
    addNewTodo: function(){
      this.todos.push( this.todo );
    },
    deleteTodo: function(){
      this.todos.shift( this.todo )
    },
  }
});

这里有一个示例 JSfiddle:https ://jsfiddle.net/mercenariomode/gwd34815/1/

4

2 回答 2

2

您需要更改对象引用,但在您的情况下,最好将“v-model”绑定到“task”属性

html代码:

<form v-on:submit.prevent="addNewTodo">
    <input type="text" v-model="task">
    <button type="submit">Add todo</button>
</form>

JS代码:

el: '#app',
  data: {
    message: 'List of things to do today',
    todos: [
      { task: 'Have breakfast', delete:'(x)'},
      { task: 'Go to the gym', delete:'(x)'},
      { task: 'Study Vuejs', delete:'(x)'}
    ],
    task: '',
}

并在 addNewTodo 方法中实现将对象添加到数组的逻辑

addNewTodo: function(){
        let todo = {task: this.task, delete: '(x)'};
        this.todos.push(todo);

        this.task = ''; // clear data in input
},

JSFiddle:https ://jsfiddle.net/nm29yq7d/1/

于 2019-02-17T23:31:05.907 回答
1

您总是引用该属性,您应该正确克隆它,例如:

 let t={};
 Object.assign(t,this.todo)
 this.todos.push( t );

我在您的代码中看到的另一个问题是您删除了错误的待办事项,要解决该问题,只需将所选待办事项的索引传递给deleteTodo方法,如下所示:

  <ul>
    <li v-for="(todo,i) in todos" :class="{ completed: todo.isActive }" @click="$set(todo, 'isActive', !todo.isActive)">
      {{ todo.task }} <span v-on:click="deleteTodo(i)">{{ todo.delete }}</span>
    </li>
  </ul>

并用于this.todos.splice(i,1);删除给定的 todo :

 deleteTodo: function(){
      this.todos.splice(i,1);
    }
于 2019-02-17T23:13:08.150 回答