实现Vue官方文档中的ToDo小实例

149 阅读1分钟

今天,笔者在学习Vue时,看到官方文档上有个ToDo List的小例子,心血来潮,想自己手动实现一下。因为只看不做,很多东西你并不知道你是否真正掌握,千里之行,始于足下,就当用来鼓励自己吧,哈哈哈。下面是代码部分。和官网给出的代码稍有不同,不过原理都是一样的。最终都能实现我们想要的功能。

<body>
  <div id="todo-list">
    <form @submit.prevent = 'additem'>
      <label for="new todo">Add new todo</label>
      <input id="new todo" placeholder="add a new todo" v-model="newTodoText"/>
      <button @click.prevent = 'additem'>Add</button>
    </form>
    <ul>
      <li is="todo-item" 
          v-for="(item,index) in todos" 
          :key="item.id" 
          :title="item.title" 
          @removeitem="clear(index)"></li>
    </ul>
  </div>
  <script>
    Vue.component('todo-item',{
      template: `<li>{{title}}
                  <button @click="remove">Remove</button> 
                 </li>`,
      props:['title'],
      methods:{
        remove(){
          this.$emit('removeitem')
        }
      }
    })
  new Vue({
    el: '#todo-list',
    data: {
      newTodoText: '',
    todos: [
      {
        id: 1,
        title: 'Do the dishes',
      },
      {
        id: 2,
        title: 'Take out the trash',
      },
      {
        id: 3,
        title: 'Mow the lawn'
      }
    ],
    nextTodoId: 4
    },
    methods:{
      clear(index){
      this.todos.splice(index,1)
      },
      additem(){
        this.todos.push({
          id: this.nextTodoId++,
          title: this.newTodoText
        })
        this.newTodoText = ''
      }
    }
  })
  </script>
  </body>