使用vue写一个数组过滤方法
时间: 2024-01-27 22:05:25 浏览: 25
可以使用Vue的计算属性来实现数组过滤,实现方法如下:
```html
<template>
<div>
<input type="text" v-model="searchText" placeholder="请输入搜索关键字">
<ul>
<li v-for="item in filteredList">{{ item }}</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
list: ['apple', 'banana', 'orange', 'pear'],
searchText: ''
}
},
computed: {
filteredList() {
return this.list.filter(item => item.includes(this.searchText))
}
}
}
</script>
```
在上面的代码中,我们定义了一个 `list` 数组和一个 `searchText` 变量用于绑定搜索框的输入值。然后,我们使用计算属性 `filteredList` 来过滤数组,只显示包含搜索关键字的项。在模板中,我们使用 `v-for` 指令循环渲染过滤后的列表。
相关问题
vue的filters过滤数组
你可以使用Vue的filters来过滤数组。首先,在Vue实例中定义一个全局的filter:
```javascript
Vue.filter('filterArray', function(array, keyword) {
// 在这里编写你的过滤逻辑
});
```
然后,在模板中使用这个filter来过滤数组:
```html
<div v-for="item in myArray | filterArray('keyword')">{{ item }}</div>
```
在上面的代码中,`myArray`是你要过滤的数组,`filterArray`是你定义的filter名字,`'keyword'`是你传入的过滤关键字。你可以根据自己的需求在`filterArray`函数中编写逻辑来实现对数组的过滤操作。
过滤Vue3响应式数组
在Vue3中,可以使用 `computed` 和 `watchEffect` 来过滤响应式数组。
下面是使用 `computed` 来过滤响应式数组的示例代码:
```javascript
import { ref, computed } from 'vue'
const list = ref([
{ id: 1, name: 'apple', category: 'fruit' },
{ id: 2, name: 'banana', category: 'fruit' },
{ id: 3, name: 'carrot', category: 'vegetable' },
{ id: 4, name: 'orange', category: 'fruit' },
])
const filteredList = computed(() => {
return list.value.filter(item => item.category === 'fruit')
})
```
在上面的代码中,我们使用 `computed` 创建了一个新的响应式数组 `filteredList`,它会根据 `list` 数组中的元素进行过滤,只保留 `category` 为 'fruit' 的元素。
如果你需要在过滤条件发生变化时重新过滤数组,可以使用 `watchEffect` 监听过滤条件的变化,示例代码如下:
```javascript
import { ref, computed, watchEffect } from 'vue'
const list = ref([
{ id: 1, name: 'apple', category: 'fruit' },
{ id: 2, name: 'banana', category: 'fruit' },
{ id: 3, name: 'carrot', category: 'vegetable' },
{ id: 4, name: 'orange', category: 'fruit' },
])
const filterCategory = ref('fruit')
const filteredList = computed(() => {
return list.value.filter(item => item.category === filterCategory.value)
})
watchEffect(() => {
filteredList.value // 重新过滤数组
})
```
在上面的代码中,我们创建了一个新的响应式变量 `filterCategory`,用于存储过滤条件。然后,我们使用 `watchEffect` 监听 `filterCategory` 的变化,并在回调函数中重新过滤数组。当 `filterCategory` 发生变化时,`filteredList` 会自动更新。