vue实现列表页面
Vue 列表页面实现方案
基础列表渲染
使用 v-for 指令渲染数组数据,配合 :key 提升性能:
<template>
<ul>
<li v-for="item in items" :key="item.id">
{{ item.name }} - {{ item.price }}
</li>
</ul>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, name: '商品A', price: 100 },
{ id: 2, name: '商品B', price: 200 }
]
}
}
}
</script>
分页功能实现
通过计算属性实现分页逻辑:
<template>
<div>
<table>
<tr v-for="item in paginatedItems" :key="item.id">
<td>{{ item.name }}</td>
</tr>
</table>
<button @click="currentPage--" :disabled="currentPage === 1">上一页</button>
<span>{{ currentPage }}/{{ totalPages }}</span>
<button @click="currentPage++" :disabled="currentPage >= totalPages">下一页</button>
</div>
</template>
<script>
export default {
data() {
return {
items: [...], // 完整数据
currentPage: 1,
pageSize: 10
}
},
computed: {
totalPages() {
return Math.ceil(this.items.length / this.pageSize)
},
paginatedItems() {
const start = (this.currentPage - 1) * this.pageSize
return this.items.slice(start, start + this.pageSize)
}
}
}
</script>
搜索过滤功能
结合计算属性实现实时搜索:
<template>
<div>
<input v-model="searchQuery" placeholder="搜索...">
<ul>
<li v-for="item in filteredItems" :key="item.id">
{{ item.title }}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
searchQuery: '',
allItems: [...]
}
},
computed: {
filteredItems() {
return this.allItems.filter(item =>
item.title.toLowerCase().includes(this.searchQuery.toLowerCase())
)
}
}
}
</script>
排序功能
通过方法实现多列排序:
<template>
<table>
<thead>
<tr>
<th @click="sortBy('name')">名称</th>
<th @click="sortBy('price')">价格</th>
</tr>
</thead>
<tbody>
<tr v-for="item in sortedItems" :key="item.id">
<td>{{ item.name }}</td>
<td>{{ item.price }}</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
items: [...],
sortKey: '',
sortOrder: 1 // 1升序,-1降序
}
},
computed: {
sortedItems() {
return [...this.items].sort((a, b) => {
return a[this.sortKey] > b[this.sortKey] ? this.sortOrder : -this.sortOrder
})
}
},
methods: {
sortBy(key) {
this.sortOrder = this.sortKey === key ? -this.sortOrder : 1
this.sortKey = key
}
}
}
</script>
异步数据加载
使用 axios 获取远程数据:
<script>
import axios from 'axios'
export default {
data() {
return {
items: [],
loading: false,
error: null
}
},
async created() {
try {
this.loading = true
const response = await axios.get('/api/items')
this.items = response.data
} catch (err) {
this.error = err.message
} finally {
this.loading = false
}
}
}
</script>
性能优化建议
- 虚拟滚动:对于超长列表使用 vue-virtual-scroller 等库
- 分页加载:结合后端 API 实现真分页而非前端分页
- 防抖处理:对搜索输入框添加防抖函数
- 组件拆分:将列表项拆分为独立组件提高复用性
以上方案可根据实际需求组合使用,构建完整的列表功能。







