2
1

More than 1 year has passed since last update.

【Vue.js】TodoList 編集機能を追加

Posted at

概要

前回のtodoListに加えて編集できる機能を追加した。

まずは全体像

  • html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="css/main.css">
    <title>Vue3</title>
</head>
<body>
    <div id="app">
        <h2>Todoリスト</h2>
        <form action="">
            <input type="text" v-model="newItem">
            <button @click.prevent="addItem">登録</button>
        </form>
        <hr>
        <ul>
            <li v-for="(todo, index) in todos">
                <input type="checkbox" v-model="todo.isDone">
                <span :class="{done: todo.isDone}">{{ todo.item }}</span>
                <!-- 更新 -->
                <div v-if="todo.isActive">
                    <span >
                        <input type="text" v-model="todo.item">
                    </span>
                    <button @click="updateDone(index)">完了</button>
                </div>
                <button @click="deleteItem(index)">削除</button>
                <button v-show="!todo.isActive" @click="updateItem(index)">修正</button>
                <hr>
            </li>

        </ul>
        <pre>{{$data}}</pre>

    </div>
    <script src="https://unpkg.com/vue@3.1.5"></script>
    <script src="js/main.js"></script>



</body>
</html>
  • js
const app = Vue.createApp({
    data(){
        return {
            newItem:'',
            todos: [],
        }
    },
    methods:{
        addItem(){
            if(this.newItem === '') return //入力欄が空だった時処理を終了
            let todo = {
                item: this.newItem,
                isDone: false,
                isActive: false
            }
            this.todos.push(todo)
            this.newItem = '' //todo登録後に入力欄を空にする
        },
        deleteItem(index){
            this.todos.splice(index, 1) //第一引数は削除する配列, 第二引数は削除する範囲

        },
        updateItem(index){
            this.todos[index].isActive = true
            this.todos[index].item = this.todos[index].item
        },
        updateDone(index){
            this.todos[index].isActive = false
        }
    }
})

app.mount('#app')
  • css
#app li > span.done {
    text-decoration: line-through;
}

#app ul{
    list-style: none;
}

追加した点

  • ボタンイベントのmethodsを二つ追加。
    • updateItem(index)
      • 修正する時のボタン
    • updateDone(index)
      • 修正が完了した時のボタン
  • dataプロパティにisActiveプロパティを追加
    • v-ifにisActiveをセット
    • 修正ボタンを押した時にtrueに変更
      • 修正可能なinput要素を表示する
      • 修正完了ボタンを表示する。
      • 修正ボタンをv-showでfalseにして非表示にする。
2
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
2
1