品牌管理
分析
-
獲取到 id 和 name ,直接從 data 上面獲取
-
組織出一個物件
-
把這個物件,呼叫 陣列的 相關方法,添加到 當前 data 上的 list 中
-
注意:在Vue中,已經實作了資料的雙向系結,每當我們修改了 data 中的資料,Vue會默認監聽到資料的改動,自動把最新的資料,應用到頁面上;
div id="app">
<div >
<div >
<h3 >添加品牌</h3>
</div>
<div >
<label>
Id:
<input type="text" v-model="id">
</label>
<label>
Name:
<input type="text" v-model="name">
</label>
<!-- 在Vue中,使用事件系結機制,為元素指定處理函式的時候,如果加了小括號,就可以給函式傳參了 -->
<input type="button" value="https://www.cnblogs.com/ygjzs/p/添加" @click="add()">
<label>
搜索名稱關鍵字:
<input type="text" v-model="keywords">
</label>
</div>
</div>
<table >
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Ctime</th>
<th>Operation</th>
</tr>
</thead>
<tbody>
<!-- 之前, v-for 中的資料,都是直接從 data 上的list中直接渲染過來的 -->
<!-- 現在, 我們自定義了一個 search 方法,同時,把 所有的關鍵字,通過傳參的形式,傳遞給了 search 方法 -->
<!-- 在 search 方法內部,通過 執行 for 回圈, 把所有符合 搜索關鍵字的資料,保存到 一個新陣列中,回傳 -->
<tr v-for="item in search(keywords)" :key="item.id">
<td>{{ item.id }}</td>
<td v-text="item.name"></td>
<td>{{ item.ctime }}</td>
<td>
<a href="" @click.prevent="del(item.id)">洗掉</a>
</td>
</tr>
</tbody>
</table>
</div>
注:用了bootstrap
var vm = new Vue({
el: '#app',
data: {
id: '',
name: '',
keywords: '', // 搜索的關鍵字
list: [
{ id: 1, name: '奔馳', ctime: new Date() },
{ id: 2, name: '寶馬', ctime: new Date() }
]
},
methods: {
add() {
var car = { id: this.id, name: this.name, ctime: new Date() }
this.list.push(car)
this.id = this.name = ''
},
del(id) { // 根據Id洗掉資料
// 分析:
// 1. 如何根據Id,找到要洗掉這一項的索引
// 2. 如果找到索引了,直接呼叫 陣列的 splice 方法
/* this.list.some((item, i) => {
if (item.id == id) {
this.list.splice(i, 1)
// 在 陣列的 some 方法中,如果 return true,就會立即終止這個陣列的后續回圈
return true;
}
}) */
var index = this.list.findIndex(item => {
if (item.id == id) {
return true;
}
})
// console.log(index)
this.list.splice(index, 1)
},
search(keywords) { // 根據關鍵字,進行資料的搜索
/* var newList = []
this.list.forEach(item => {
if (item.name.indexOf(keywords) != -1) {
newList.push(item)
}
})
return newList */
// 注意: forEach some filter findIndex 這些都屬于陣列的新方法,
// 都會對陣列中的每一項,進行遍歷,執行相關的操作;
return this.list.filter(item => {
// if(item.name.indexOf(keywords) != -1)
// 注意 : ES6中,為字串提供了一個新方法,叫做 String.prototype.includes('要包含的字串')
// 如果包含,則回傳 true ,否則回傳 false
// contain
//console.log(keywords);
if (item.name.includes(keywords)) {
return item
}
})
}
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/177007.html
標籤:JavaScript
