1. 程式人生 > 其它 >vue搜尋功能實現(vue+element+vant)

vue搜尋功能實現(vue+element+vant)

template的程式碼:

//搜尋框
<el-input placeholder="請輸入..." v-model="keyword"></el-input> <button @click="search">搜尋</button>
//內容
<div v-for=(item,index) in list :key=index>{{item.title}}</div>
<div v-if="isShowTip">沒有搜尋到匹配結果</div>

data初始化:

  data() {
    return
{ keyword: "", list: [], searchList: [], isShowTip: false, }; },

methods:

  search() {
      this.isShowTip = false;
      if (this.keyword == "") {
        this.$toast("請輸入相關內容搜尋");
        return;
      }
      this.$axios.get( "../../json/getAll.json")
        .then((res) 
=> {this.list= res.data.data; }) .then(() => { this.searchList = []; this.list.forEach((item) => { if (item.title.indexOf(this.keyword) > -1) { this.searchList.push(item); } }); if (this.searchList.length == 0
) { this.isShowTip = true; } this.searchList.map((item) => { item.title= this.brightKeyword(item.title); }); }); }, brightKeyword(val) { let keyword = this.keyword; if (val.indexOf(keyword) !== -1) { return val.replace(keyword, `${keyword}`); } else { return val; } },