LoginSignup
1
1

More than 3 years have passed since last update.

Vue.jsでTodoリストを作ってみた

Posted at

はじめに

Vue.jsを学習し始めて2週間ほど経ったのでTodoリストを作ってみました!

書き方

Vue.jsは書き方が何種類かありますが、今回はHTML,Javascriptのファイルに分けて書きたいと思います。

ディレクトリツリー

root/
 ┝ index.html
 └  javascript/
  └ app.js

HTMLのコード

index.html
<!DOCTYPE html>
<html lang="ja">
<head>
 <title>Todoリスト</title>
 <!-- CDNにてVue.jsを導入 -->
 <script src="https://unpkg.com/vue@2.5.17"></script>
</head>
<body>
 <div id="app">
    <!-- 新しいタスクの入力フォーム -->
    <input type="text" placeholder="新しいタスク" v-model="newTask">
    <input type="submit" value="追加" @click="addTask">

    <!-- 達成率を表示 -->
    達成数: {{ completedTasks }} / {{ totalTasks }}

    <!-- タスクの一覧 -->
    <ul>
      <li v-for="(task, index) in tasks" :key="task.title">
      {{ task.title }}
      <button v-if="task.done" @click="completed(index)">完了</button>
      <label v-else>完了済み</label>
      <button @click="deleteTask(index)">削除</button>
      </li>
    </ul>
  </div>
  <script src="javascript/app.js"></script>
</body>

Javascriptのコード

app.js
const tasks = [
  {
    title: 'sample',
    done: false
  }
]

var app = new Vue({
  el: "#app",
  data: {
    tasks: tasks,
    newTask: null
  },
  methods: {
    completed: function(index) {
      this.tasks[index].done = true
    },
    addTask: function() {
      if(newTask){
        this.tasks.push({ title: this.newTask, done: false })
        this.newTask = null
      }
    },
    deleteTask: function(index) {
      this.tasks.splice(index, 1)
    }
  },
  computed: {
    completedTasks: function() {
      var count = 0
      for(let i = 0; i < this.tasks.length; i++){
        if(this.tasks[i].done){
          count++
        }
      }
      return count
    },
    totalTasks: function() {
      return this.tasks.length
    }
  }
})

実行結果

最初の画面
スクリーンショット 2020-02-08 23.02.06.png
完了ボタンを押した後
スクリーンショット 2020-02-08 23.02.45.png
残りの動作は省略

まとめ

今回はCDNでお手軽にVue.jsを導入してTodoリストを作成しました。
今後はVueCLIを使用して導入し単一ファイルでアプリケーションを作成したいと思います。

1
1
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
1
1