帮我写个vue排序
以下是一个简单的Vue排序示例,使用了v-for指令来循环遍历数组,并使用v-bind指令将数组元素绑定到页面上,最后使用v-on指令绑定一个点击事件来触发排序操作。
<template>
<div>
<button @click="sortAscending">升序排列</button>
<button @click="sortDescending">降序排列</button>
<ul>
<li v-for="item in sortedItems" :key="item.id">{{ item.value }}</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, value: 5 },
{ id: 2, value: 1 },
{ id: 3, value: 3 },
{ id: 4, value: 2 },
{ id: 5, value: 4 }
]
}
},
computed: {
sortedItems() {
return this.items.sort((a, b) => a.value - b.value)
}
},
methods: {
sortAscending() {
this.items.sort((a, b) => a.value - b.value)
},
sortDescending() {
this.items.sort((a, b) => b.value - a.value)
}
}
}
</script>
上面的代码中,我们使用了computed属性来返回一个已排序的数组,当sortAscending或sortDescending方法被调用时,它们将更新原始数据并重新计算已排序的数组。最后,我们使用v-for指令来循环遍历sortedItems数组,将每个元素的值绑定到页面上。
原文地址: https://www.cveoy.top/t/topic/Yrr 著作权归作者所有。请勿转载和采集!