需求:
①能够实现记录重复数据
②全部清空
③单条记录清空
页面效果:
代码:
<!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>