vue实现list
Vue 实现列表功能
在 Vue 中实现列表功能通常使用 v-for 指令,结合数组数据动态渲染列表项。以下是几种常见的实现方式:
基础列表渲染
<template>
<ul>
<li v-for="(item, index) in items" :key="index">
{{ item.text }}
</li>
</ul>
</template>
<script>
export default {
data() {
return {
items: [
{ text: 'Item 1' },
{ text: 'Item 2' },
{ text: 'Item 3' }
]
}
}
}
</script>
带过滤功能的列表
<template>
<div>
<input v-model="searchQuery" placeholder="Search...">
<ul>
<li v-for="item in filteredItems" :key="item.id">
{{ item.name }}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
searchQuery: '',
items: [
{ id: 1, name: 'Apple' },
{ id: 2, name: 'Banana' },
{ id: 3, name: 'Orange' }
]
}
},
computed: {
filteredItems() {
return this.items.filter(item =>
item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
)
}
}
}
</script>
可排序列表
<template>
<div>
<button @click="sort('asc')">Sort Ascending</button>
<button @click="sort('desc')">Sort Descending</button>
<ul>
<li v-for="item in sortedItems" :key="item.id">
{{ item.name }} - {{ item.price }}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
sortDirection: 'asc',
items: [
{ id: 1, name: 'Apple', price: 1.2 },
{ id: 2, name: 'Banana', price: 0.8 },
{ id: 3, name: 'Orange', price: 1.5 }
]
}
},
computed: {
sortedItems() {
return [...this.items].sort((a, b) => {
return this.sortDirection === 'asc'
? a.price - b.price
: b.price - a.price
})
}
},
methods: {
sort(direction) {
this.sortDirection = direction
}
}
}
</script>
带分页的列表
<template>
<div>
<ul>
<li v-for="item in paginatedItems" :key="item.id">
{{ item.name }}
</li>
</ul>
<button @click="prevPage" :disabled="currentPage === 1">Previous</button>
<span>Page {{ currentPage }} of {{ totalPages }}</span>
<button @click="nextPage" :disabled="currentPage === totalPages">Next</button>
</div>
</template>
<script>
export default {
data() {
return {
currentPage: 1,
itemsPerPage: 5,
items: [
// 假设这里有大量数据
]
}
},
computed: {
totalPages() {
return Math.ceil(this.items.length / this.itemsPerPage)
},
paginatedItems() {
const start = (this.currentPage - 1) * this.itemsPerPage
const end = start + this.itemsPerPage
return this.items.slice(start, end)
}
},
methods: {
nextPage() {
if (this.currentPage < this.totalPages) {
this.currentPage++
}
},
prevPage() {
if (this.currentPage > 1) {
this.currentPage--
}
}
}
}
</script>
动态加载更多列表
<template>
<div>
<ul>
<li v-for="item in visibleItems" :key="item.id">
{{ item.title }}
</li>
</ul>
<button
@click="loadMore"
v-if="hasMoreItems"
>
Load More
</button>
</div>
</template>
<script>
export default {
data() {
return {
visibleCount: 5,
items: [
// 假设这里有大量数据
]
}
},
computed: {
visibleItems() {
return this.items.slice(0, this.visibleCount)
},
hasMoreItems() {
return this.visibleCount < this.items.length
}
},
methods: {
loadMore() {
this.visibleCount += 5
}
}
}
</script>
以上示例展示了 Vue 中实现列表的几种常见模式,可以根据实际需求选择合适的实现方式或组合使用这些技术。







