Vue入门-使用Vue2完成简单的记事本Demo

需求:

①能够实现记录重复数据

②全部清空

③单条记录清空

页面效果:

代码:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vue2 记事本</title>
    <style>
        body {
            font-family: Arial, sans-serif;
        }

        .note-container {
            max-width: 600px;
            margin: 0 auto;
        }

        textarea {
            resize: vertical;
        }
    </style>
</head>

<body>
    <div id="app" class="note-container">
        <textarea v-model="noteContent" class="form-control"></textarea>
        <div class="mt-3">
            <button @click="saveNote" class="btn btn-primary me-2">保存</button>
            <button @click="clearNote" class="btn btn-secondary">清空</button>
        </div>
        <ul class="list-group mt-3" v-if="savedNotes.length > 0">
            <li class="list-group-item" v-for="note in savedNotes" :key="note">
                {{ note }}
                <button @click="deleteNote(note)" class="btn btn-danger btn-sm float-right">删除</button>
            </li>
        </ul>
    </div>

    <script src="js/vue.js"></script>
    <script>
        new Vue({
            el: '#app',
            data: {
                noteContent: '',
                savedNotes: []
            },
            methods: {
                saveNote() {
                    const note = this.noteContent.trim();
                    if (note !== '') {
                        this.savedNotes.push(note);
                        localStorage.setItem('notes', JSON.stringify(this.savedNotes));
                        this.noteContent = '';
                        alert('笔记已保存!');
                    }
                },
                clearNote() {
                    this.noteContent = '';
                    this.savedNotes = [];
                    localStorage.removeItem('notes');
                },
                deleteNote(noteToDelete) {
                    this.savedNotes = this.savedNotes.filter(note => note !== noteToDelete);
                    localStorage.setItem('notes', JSON.stringify(this.savedNotes));
                }
            },
            mounted() {
                const savedNotes = localStorage.getItem('notes');
                if (savedNotes) {
                    this.savedNotes = JSON.parse(savedNotes);
                }
            }
        });
    </script>
</body>

</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值