品牌管理
分析
獲取到 id 和 name ,直接從 data 上面獲取
組織出一個(gè)對(duì)象
把這個(gè)對(duì)象,調(diào)用 數(shù)組的 相關(guān)方法,添加到 當(dāng)前 data 上的 list 中
注意:在Vue中,已經(jīng)實(shí)現(xiàn)了數(shù)據(jù)的雙向綁定,每當(dāng)我們修改了 data 中的數(shù)據(jù),Vue會(huì)默認(rèn)監(jiān)聽到數(shù)據(jù)的改動(dòng),自動(dòng)把最新的數(shù)據(jù),應(yīng)用到頁(yè)面上;
div id="app">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">添加品牌</h3>
</div>
<div class="panel-body form-inline">
<label>
Id:
<input type="text" class="form-control" v-model="id">
</label>
<label>
Name:
<input type="text" class="form-control" v-model="name">
</label>
<!-- 在Vue中,使用事件綁定機(jī)制,為元素指定處理函數(shù)的時(shí)候,如果加了小括號(hào),就可以給函數(shù)傳參了 -->
<input type="button" value="添加" class="btn btn-primary" @click="add()">
<label>
搜索名稱關(guān)鍵字:
<input type="text" class="form-control" v-model="keywords">
</label>
</div>
</div>
<table class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Ctime</th>
<th>Operation</th>
</tr>
</thead>
<tbody>
<!-- 之前, v-for 中的數(shù)據(jù),都是直接從 data 上的list中直接渲染過來的 -->
<!-- 現(xiàn)在, 我們自定義了一個(gè) search 方法,同時(shí),把 所有的關(guān)鍵字,通過傳參的形式,傳遞給了 search 方法 -->
<!-- 在 search 方法內(nèi)部,通過 執(zhí)行 for 循環(huán), 把所有符合 搜索關(guān)鍵字的數(shù)據(jù),保存到 一個(gè)新數(shù)組中,返回 -->
<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: '', // 搜索的關(guān)鍵字
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) { // 根據(jù)Id刪除數(shù)據(jù)
// 分析:
// 1. 如何根據(jù)Id,找到要?jiǎng)h除這一項(xiàng)的索引
// 2. 如果找到索引了,直接調(diào)用 數(shù)組的 splice 方法
/* this.list.some((item, i) => {
if (item.id == id) {
this.list.splice(i, 1)
// 在 數(shù)組的 some 方法中,如果 return true,就會(huì)立即終止這個(gè)數(shù)組的后續(xù)循環(huán)
return true;
}
}) */
var index = this.list.findIndex(item => {
if (item.id == id) {
return true;
}
})
// console.log(index)
this.list.splice(index, 1)
},
search(keywords) { // 根據(jù)關(guān)鍵字,進(jìn)行數(shù)據(jù)的搜索
/* var newList = []
this.list.forEach(item => {
if (item.name.indexOf(keywords) != -1) {
newList.push(item)
}
})
return newList */
// 注意: forEach some filter findIndex 這些都屬于數(shù)組的新方法,
// 都會(huì)對(duì)數(shù)組中的每一項(xiàng),進(jìn)行遍歷,執(zhí)行相關(guān)的操作;
return this.list.filter(item => {
// if(item.name.indexOf(keywords) != -1)
// 注意 : ES6中,為字符串提供了一個(gè)新方法,叫做 String.prototype.includes('要包含的字符串')
// 如果包含,則返回 true ,否則返回 false
// contain
//console.log(keywords);
if (item.name.includes(keywords)) {
return item
}
})
}
});