溫馨提示×

vue如何實現輸入框搜索功能

vue
小億
536
2023-08-03 23:02:25
欄目: 編程語言

在Vue中實現輸入框搜索功能也有多種方法,以下是其中一種常見的做法:

1. 創建一個Vue組件,用于處理搜索邏輯和展示搜索結果。

<template>

  <div>

    <input v-model="searchText" @input="handleSearch" placeholder="輸入關鍵字搜索">

    <ul>

      <li v-for="item in searchResults" :key="item.id">{{ item.name }}</li>

    </ul>

  </div>

</template>

<script>

export default {

  data() {

    return {

      searchText: '',

      list: [

        { id: 1, name: 'Item 1' },

        { id: 2, name: 'Item 2' },

        { id: 3, name: 'Item 3' },

      ],

    };

  },

  computed: {

    searchResults() {

      if (this.searchText) {

        return this.list.filter(item => {

          return item.name.toLowerCase().includes(this.searchText.toLowerCase());

        });

      } else {

        return this.list;

      }

    },

  },

  methods: {

    handleSearch() {

      // 可以在這里進行其他處理,例如發送網絡請求獲取搜索結果

    },

  },

};

</script>

在上面的示例中,我們使用了一個輸入框(<input>)來獲取用戶的搜索關鍵字,并使用v-model指令將輸入框的值綁定到searchText數據屬性上。

在computed計算屬性中,我們根據searchText的值對列表項進行過濾。如果searchText不為空,則使用filter()方法來過濾列表項,只顯示包含搜索關鍵字的項;如果searchText為空,則返回完整列表。

在模板中使用v-for指令遍歷searchResults,并通過:key綁定每個列表項的唯一標識符。

可以根據需要自定義樣式、添加更多搜索條件或使用其他方法來實現輸入框搜索功能。另外,在handleSearch方法中,你可以進行其他處理,例如發送網絡請求獲取搜索結果。



0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女