Vue2 实现 Todolist
HTML:
<div id="app">
<h1>Todolist</h1>
<input v-model="newItem" @keyup.enter="addItem" placeholder="Add new item">
<ul>
<li v-for="(item, index) in items" :key="index">
<input type="checkbox" v-model="item.completed">
<span :class="{ completed: item.completed }">{{ item.text }}</span>
<button class="delete" @click="removeItem(index)">Remove</button>
</li>
</ul>
<p>Total items: {{ items.length }}</p>
<p>Completed items: {{ completedItems }}</p>
</div>
JavaScript:
new Vue({
el: '#app',
data() {
return {
newItem: '',
items: [
{ text: 'Learn Vue.js', completed: false },
{ text: 'Build a todolist', completed: true }
]
}
},
methods: {
addItem() {
if (this.newItem.trim()) {
this.items.push({ text: this.newItem, completed: false })
this.newItem = ''
}
},
removeItem(index) {
this.items.splice(index, 1)
}
},
computed: {
completedItems() {
return this.items.filter(item => item.completed).length
}
}
})
CSS:
.completed {
text-decoration: line-through;
}
Vue3 实现 Todolist
HTML:
<div id="app">
<h1>Todolist</h1>
<input v-model="newItem" @keyup.enter="addItem" placeholder="Add new item">
<ul>
<li v-for="(item, index) in items" :key="index">
<input type="checkbox" v-model="item.completed">
<span :class="{ completed: item.completed }">{{ item.text }}</span>
<button class="delete" @click="removeItem(index)">Remove</button>
</li>
</ul>
<p>Total items: {{ items.length }}</p>
<p>Completed items: {{ completedItems }}</p>
</div>
JavaScript:
const app = Vue.createApp({
data() {
return {
newItem: '',
items: [
{ text: 'Learn Vue.js', completed: false },
{ text: 'Build a todolist', completed: true }
]
}
},
methods: {
addItem() {
if (this.newItem.trim()) {
this.items.push({ text: this.newItem, completed: false })
this.newItem = ''
}
},
removeItem(index) {
this.items.splice(index, 1)
}
},
computed: {
completedItems() {
return this.items.filter(item => item.completed).length
}
}
})
app.mount('#app')
CSS:
.completed {
text-decoration: line-through;
}