大家今天vue課程實戰系列又更新了,今天我們繼續上次更新的内容繼續實作搜尋框動态時時搜尋
效果圖如下:
在做案例之前,先介紹下用到的新知識點,es6新文法 includes 先看一個例子讓我們了解下這個方法的使用
執行個體
檢測數組site是否包含 runoob :let site = ['runoob', 'google', 'taobao'];
site.includes('runoob');
// true
site.includes('baidu');
// false
下面開始我們的案例講解,在這個案例中我們會使用多個方法實作這個搜尋框搜尋的效果實作,使用函數,使用計算屬性都可以實作最終的效果,讓我們一起學習下。
首先 我們先使用第一種方法用普通函數實作:
在methods 方法中加入 search方法,方法中加入參數 search(keywords)
模版中雙向綁定 keywords
代碼片段如下:
{{ item.id }}{{ item.name }}{{ item.ctime }} 删除
完整的html代碼:
添加品牌
Id:
Name:
搜尋名名稱關鍵字:
IdNameCtimeOperation
{{ item.id }}{{ item.name }}{{ item.ctime }} 删除
vue中加入keywords 設定一個預設值data : {
id : '',
name : '',
keywords: '',
list : [
{ id : 1, name : '奔馳', ctime: new Date()},
{ id : 2, name : '寶馬', ctime: new Date()},
]
},
方法中加入 search 這個裡有兩種方法可以實作先介紹正常思維的實作search(keywords){
var newList =[];
this.list.forEach(iterm=>{
if (iterm.name.indexOf(keywords) !== -1) {
newList.push(iterm);
}
});
return newList;
}
上面使用了indexOf方法實作查找字元串然後更新數組
方法2 :使用 es6 新文法 includes
代碼片段:search(keywords){
return this.list.filter(iterm=>{
if (iterm.name.includes(keywords)) {
return iterm;
}
});
}
這是就是本文開頭介紹的includes方法結合過濾器實作的。本文是實戰課程,有關過濾器的使用請查閱相關資料。
還可以使用計算屬性 computed 實作搜尋框的過濾功能
下面我們把上面的html代碼改造下。片段如下:
{{ item.id }}{{ item.name }}{{ item.ctime }} 删除
這裡我們去除了search方法使用計算屬性 newList來實作同樣的效果
我們 在vue中加入計算屬性 newList 代碼片段如下:computed : {
newList : function() {
return this.list.filter(iterm=>{
if (iterm.name.includes(this.keywords)) {
return iterm;
}
});
}
}
我們使用計算屬性之前要把之前定義methods search方法要删除掉,切記!
最後附上完整代碼html>
購物車示例
添加品牌
Id:
Name:
搜尋名名稱關鍵字:
IdNameCtimeOperation
{{ item.id }}{{ item.name }}{{ item.ctime }} 删除
var vue = 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);
},
del(id) {
//第一種方法,可以實作不推薦
//推薦使用内部的findIndex實作擷取索引
var index = this.list.findIndex(item=>{
if(item.id === id) {
return true;
}
});
this.list.splice(index,1);
},
//方法1 使用indexOf
//方法2 使用 es6新文法 includes
},
//方法3 使用計算屬性
computed : {
newList : function() {
return this.list.filter(iterm=>{
if (iterm.name.includes(this.keywords)) {
return iterm;
}
});
}
}
});
今天文章更新到這,下次我們會接着這個案例繼續更新,感謝大家的閱讀!