劃重點:
- lable 標籤
- keyup:鍵盤事件
- 標籤內添加樣式:style
- 使用事件修飾符:prevent
- forEach :遍歷 數組
- indexOf: 可以返回要查詢的某個字符串值在整個字符串中首次出現的位置下標
- findIndex:返回傳入一個測試條件(函數)符合條件數組的首個元素的位置
- splice:向/從數組中添加/刪除項目,然後返回被刪除後的新的項目數組
黑椒蟹 一對:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="./lib/vue-2.6.10.js"></script>
<title>增刪查功能</title>
</head>
<body>
<div id="app">
<h3 style="background-color: burlywood ; height: 50px;">添加/查詢/刪除功能 使用案例</h3>
<table >
<tbody>
<th>Id:</th>
<th>Name:</th>
<th>Operation:</th>
</tbody>
</table>
<br>
<label>Id:
<input type="text" v-model="id">
</label>
<label>Name:
<input type="text" v-model="name" @keyup.enter="add">
</label>
<input type="button" value="添加" v-on:click="add">
<input type="text" id="inputs" v-model="keywords" @keyup.enter="search">查詢
<br>
<p v-for="item in search1(keywords)" style="background-color: cadetblue" v-bind:key="item.id">
<input type="checkbox">
ID:{{ item.id }} Name:{{ item.name }}
<!-- <input type="button" value="刪除" v-on:click="del(item.id)"> -->
<a href="" @click.prevent="del(item.id)">刪除</a>
</p>
<br>
<br>
<br>
<p v-for="item in newListData" style="background-color: cadetblue" v-bind:key="item.id">
<input type="checkbox">
ID:{{ item.id }} Name:{{ item.name }}
<!-- <input type="button" value="刪除" v-on:click="del(item.id)"> -->
<a href="" @click.prevent="del(item.id)">刪除</a>
</p>
</div>
<script>
var vm = new Vue({
el: '#app',
data: {
id: null,
name: null,
keywords: '',
listData: [
{ id: 11, name: '寶馬' },
{ id: 12, name: '奔馳' },
{ id: 13, name: '法拉利' }
]
,
newListData: [
{ id: 1001, name: '寶馬' }
]
},
methods: {
add() {
if (this.id != null && this.name != null) {
this.listData.push({ id: this.id, name: this.name })
this.id = this.name = null
}
else {
alert("請正確輸入內容~~~")
}
},
del: function (id) {
var index = this.listData.findIndex((item) => {
if (item.id == id) {
return true
}
})
return this.listData.splice(index, 1);
},
search() {
var keywords = document.getElementById("inputs").value;
alert(keywords)
if (keywords == null) {
return this.listData
}
var newList = [];
this.listData.forEach(item => {
if (item.name.indexOf(keywords) != -1) {
newList.push(item)
}
});
this.newListData = newList
return newList
},
search1(keywords) {
if (keywords == null) {
return this.listData
}
var newList = [];
this.listData.forEach(item => {
if (item.name.indexOf(keywords) != -1) {
newList.push(item)
}
});
return newList
}
}
})
</script>
</body>
</html>
運行圖1:
運行圖2:添加三個item
通過“紅”關鍵字查詢