技術ブログ

(技術系中心)基本自分用備忘録なので、あくまで参考程度でお願いします。

vue.jsで超簡易的なtodo作成

vue.jsで超簡易的なtodo作成

<div id="app">
  <h2>Todos list</h2>
  <!-- 実際にsubmitするのを防ぐ -->
  <form v-on:submit.prevent>
    <!-- newItemを双方向データバインディングする -->
    <input type="text" v-model="newItem">
    <!-- ボタンが押された時にaddItemメソッドを発動させる -->
    <button v-on:click="addItem">
      ADD
    </button>
    <ul>
      <!-- todos配列をv-forで一つづつ表示 -->
      <!-- todo -> 内容、 index -> インデックス番号 -->
      <li v-for="(todo, index) in todos">
      <!-- isDoneとデータバインディングしてtrueの時はチェックボックスにマークを入れる -->
      <input type="checkbox" v-model="todo.isDone">
      <!-- todo.isDoneがtrueの時だけクラス割り当てするようにする -->
      <span v-bind:class="{ done: todo.isDone }"> {{ todo.item }}</span>
      <!-- Deleteボタンが押された時にdeleteItemメソッドを呼び出す。
      消す内容は引数のindexで渡されたもの -->
       <button v-on:click="deleteItem(index)">
         Delete
       </button>
      </li>
    </ul>
    <pre>{{ $data }}</pre>
  </form>
</div>
new Vue({
    /* #appをマウントする */
  el: "#app",
  data: {
        newItem: "",
    todos: []
  },
  methods: {
        addItem: function(event) {
        /* newItemがからの文字列の時はretrunする(つまり何もしない) */
      if (this.newItem == "") return;

      var todo = {
        item: this.newItem,
        isDone: false
      };
      
      /* 入力されたtodoをtodos配列に代入する */
      this.todos.push(todo);
      /* データバイディングされたnewItemにからの文字列を代入 */
      this.newItem = "";
    },
    
    deleteItem: function(index) {
        /* jsのspliceメソッドで削除 */
        this.todos.splice(index, 1)
    }
  }
})
#app ul {
  list-style: none;
}

#app li > span.done {
  text-decoration: line-through;
}

結果

https://jsfiddle.net/hiroki1205/4e06y1q7/