LoginSignup
11
17

More than 5 years have passed since last update.

Vue.jsを使って簡単なToDoリストを作成してみた

Last updated at Posted at 2017-06-01

MVVMの中でもシンプルで学習障壁が低いと言われている「Vue.js」を使って、ToDoリストを作成してみました。(追加と削除のみの機能しかもたない簡単なToDOリストです。)

学習した内容の整理も兼ねて、記述したコードを紹介したいと思います。

※今回はVue.js v2.3.3を使用しています。

ViewModel

scriptの記述は下記の通り▼


new Vue({
el: '#js-todoList',
data: {
  newItem: "",
  todos: []
},
methods: {
  addItem: function(event) {
    event.preventDefault();
    if (this.newItem == "") return;
    this.todos.push({
      item: this.newItem
    });
    this.newItem = "";
  },
  deleteItem: function(todo) {
    var index = this.todos.indexOf(todo);
    this.todos.splice(index, 1)
  }
}
})

まずはインプットしたデータを取得するnewItemとデータを格納する配列を定義。
さらにmethodsで下記の2つのfunctionを作成。

  • 入力したデータを配列に格納するaddTodo
  • 削除ボタンを押されたItemを配列から消すdeleteTodo

View(HTML)

htmlはこちら▼

<div id="js-todoList">
  <form>
    <input type="text" v-model="newItem">
    <button v-on:click="addItem">追加</button>
  </form>
  <ul>
    <li v-for="todo in todos">
      {{todo.item}}
      <button v-on:click="deleteItem(todo)">削除</button>
    </li>
  </ul>
</div>

Vue.jsにはディレクティブと呼ばれるhtmlに組み込む機能があります。これはHTMLに独自の属性を付与することで、DOM操作を行う機能です。
今回は下記3つのディレクティブを使用しています。

v-model
inputされた値をバインディングして取得する機能

v-on
DOM イベントの購読、イベント発火時のJavaScriptの実行をハンドリングする機能。ここではaddItem、deleteItemの2つのfunctionを制御しています。

v-for
配列に格納されたデータを描写する機能

まとめ

今回は簡単なToDOリストを作成してみました。まだまだ知らない機能がたくさんあるので、様々な制作物を通してvue.jsの理解を深めていきたいと思います。

11
17
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
17