vue实现列表查询
Vue 实现列表查询的方法
基础列表渲染
使用 v-for 指令渲染数组数据,配合 key 属性提升性能:
<template>
<ul>
<li v-for="item in items" :key="item.id">
{{ item.name }}
</li>
</ul>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' }
]
}
}
}
</script>
动态过滤查询
通过计算属性实现实时搜索过滤:

<template>
<input v-model="searchQuery" placeholder="Search...">
<ul>
<li v-for="item in filteredItems" :key="item.id">
{{ item.name }}
</li>
</ul>
</template>
<script>
export default {
data() {
return {
searchQuery: '',
items: [
{ id: 1, name: 'Apple' },
{ id: 2, name: 'Banana' }
]
}
},
computed: {
filteredItems() {
return this.items.filter(item =>
item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
)
}
}
}
</script>
分页功能实现
结合分页参数进行数据切片:

<template>
<ul>
<li v-for="item in paginatedItems" :key="item.id">
{{ item.name }}
</li>
</ul>
<button @click="prevPage">Previous</button>
<span>Page {{ currentPage }}</span>
<button @click="nextPage">Next</button>
</template>
<script>
export default {
data() {
return {
currentPage: 1,
itemsPerPage: 5,
items: [...] // 假设有大量数据
}
},
computed: {
paginatedItems() {
const start = (this.currentPage - 1) * this.itemsPerPage
return this.items.slice(start, start + this.itemsPerPage)
}
},
methods: {
nextPage() {
if (this.currentPage * this.itemsPerPage < this.items.length) {
this.currentPage++
}
},
prevPage() {
if (this.currentPage > 1) {
this.currentPage--
}
}
}
}
</script>
异步数据加载
通过 API 获取远程数据:
<template>
<ul v-if="!loading">
<li v-for="item in items" :key="item.id">
{{ item.name }}
</li>
</ul>
<div v-else>Loading...</div>
</template>
<script>
export default {
data() {
return {
loading: true,
items: []
}
},
async created() {
try {
const response = await fetch('https://api.example.com/items')
this.items = await response.json()
} catch (error) {
console.error(error)
} finally {
this.loading = false
}
}
}
</script>
复合查询功能
结合多个过滤条件和排序:
<template>
<input v-model="filters.name" placeholder="Name">
<select v-model="filters.category">
<option value="">All</option>
<option value="electronics">Electronics</option>
</select>
<ul>
<li v-for="item in processedItems" :key="item.id">
{{ item.name }} - {{ item.price }}
</li>
</ul>
</template>
<script>
export default {
data() {
return {
filters: {
name: '',
category: ''
},
items: [...]
}
},
computed: {
processedItems() {
return this.items
.filter(item => {
const nameMatch = item.name.toLowerCase()
.includes(this.filters.name.toLowerCase())
const categoryMatch = this.filters.category === ''
|| item.category === this.filters.category
return nameMatch && categoryMatch
})
.sort((a, b) => a.price - b.price)
}
}
}
</script>
使用第三方库
对于复杂场景可考虑使用专门库如 vue-infinite-loading 实现无限滚动,或 vue-tables-2 实现高级表格功能。安装后按文档配置即可快速实现复杂列表功能。






