![image]()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<h1>小黑的書架</h1>
<ul>
<li v-for="item in list" :key="item.id">
<span>{{ item.name }}</span>
<span>{{ item.author }}</span>
<!-- 注冊id事件,通過 id 進行刪除數組中的 對應項 -->
<button @click="del(item.id)">刪除</button>
</li>
</ul>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2.7.16/dist/vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
list: [
{ id: 1, name: '《紅樓夢》', author: '曹雪芹' },
{ id: 2, name: '《西游記》', author: '吳承恩' },
{ id: 3, name: '《水滸傳》', author: '施耐庵' },
{ id: 4, name: '《三國演義》', author: '羅貫中' }
]
},
methods: {
del(id) {
// console.log('刪除id')
// filter 過濾器 會創建一個新的數組,保留滿足條件的,這點要記住,并且是淺拷貝
this.list = this.list.filter(item => item.id !== id)
}
}
})
</script>
</body>
</html>