Vue Day1【綜合案例】小黑記事本
功能總結:
① 列表渲染:v-for key 的設置 {{ }} 插值表達式
② 刪除功能:v-on 調用傳參 filter 過濾 覆蓋修改原數組
③ 添加功能:v-model 綁定 unshift 修改原數組添加
④ 底部統計 和 清空
(1)數組.length累計長度
(2)覆蓋數組清空列表
(3)v-show 控制隱藏
trim()方法用于移除字符串兩端的空白字符(包括空格、制表符、換行符等),并返回一個新的字符串,而不會修改原始字符串。

<body>
<!-- 主體區域 -->
<section id="app">
<!-- 輸入框 -->
<header class="header">
<h1>小黑記事本</h1>
<input v-model="todoName" placeholder="請輸入任務" class="new-todo" />
<button @click="add" class="add">添加任務</button>
</header>
<!-- 列表區域 -->
<section class="main">
<ul class="todo-list">
<!-- 別忘了 :key -->
<li class="todo" v-for="(item,index) in list" :key="item.id">
<div class="view">
<span class="index">{{index+1}}.</span> <label>{{ item.name }}</label>
<button @click="del(item.id)" class="destroy"></button>
</div>
</li>
</ul>
</section>
<!-- 統計和清空 → 如果沒有任務了,就隱藏底部 → v-show -->
<footer v-show="list.length>0" class="footer">
<!-- 統計 -->
<span class="todo-count">合 計:<strong> {{ list.length }} </strong></span>
<!-- 清空 -->
<button @click="list=[]" class="clear-completed">
清空任務
</button>
</footer>
</section>
<!-- 底部 -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
// 添加功能
// 1. 通過 v-model 綁定 輸入框 → 實時獲取表單元素的內容
// 2. 點擊按鈕,進行新增
const app = new Vue({
el: '#app',
data: {
// 這里加一個 todoName
todoName: '',
list: [
{ id: 1, name: '跑步一公里' },
{ id: 2, name: '跳繩半小時' },
{ id: 3, name: '游泳一小時' },
]
},
methods: {
del(id) {
// console.log(id) filter 保留所有不等于該 id 的項
this.list = this.list.filter(item => item.id !== id)
},
add() {
if (this.todoName.trim() === '') {
alert("您的輸入為空")
return
}
this.list.unshift({
id: +new Date(),
name: this.todoName
})
// console.log(this.list)
this.todoName = ''
}
}
})
</script>
</body>

浙公網安備 33010602011771號