在Vue3中,可以使用计算属性来实现搜索功能。下面是一个简单的例子:

<template>
  <div>
    <input v-model="search" placeholder="Search...">
    <ul>
      <li v-for="item in filteredItems" :key="item.id">{{ item.name }}</li>
    </ul>
  </div>
</template>

<script>
import { ref, computed } from 'vue'

export default {
  setup() {
    const items = ref([
      { id: 1, name: 'Apple' },
      { id: 2, name: 'Banana' },
      { id: 3, name: 'Cherry' },
      { id: 4, name: 'Durian' },
      { id: 5, name: 'Eggplant' },
    ])
    const search = ref('')
    const filteredItems = computed(() => {
      return items.value.filter(item => {
        return item.name.toLowerCase().includes(search.value.toLowerCase())
      })
    })
    return {
      items,
      search,
      filteredItems,
    }
  },
}
</script>

在这个例子中,我们有一个输入框,用户可以在其中输入搜索关键字。我们使用v-model指令将用户输入的内容绑定到search变量上。

我们还有一个items变量,它是一个包含多个对象的数组,每个对象包含一个id和一个name属性。

我们使用Vue3中的ref函数来创建响应式的变量,这样当itemssearch变量的值发生变化时,页面会自动更新。

我们使用computed函数来创建一个计算属性filteredItems,它会根据search变量的值来过滤items数组中的元素。具体来说,我们使用filter函数来过滤数组,只保留那些name属性包含search变量值的元素。

最后,我们在模板中使用v-for指令来遍历filteredItems数组,将每个元素的name属性显示在页面上。

这样,当用户在输入框中输入关键字时,页面会自动更新,只显示那些包含关键字的元素

vue3中用计算属性写个搜索功能

原文地址: https://www.cveoy.top/t/topic/hkQc 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录