当前位置:首页 > VUE

vue实现排序

2026-03-27 12:02:00VUE

实现数组排序

在Vue中实现数组排序可以通过计算属性或方法对数组进行处理。假设有一个数据列表需要根据特定条件排序:

data() {
  return {
    items: [
      { id: 1, name: 'Item C', price: 30 },
      { id: 2, name: 'Item A', price: 10 },
      { id: 3, name: 'Item B', price: 20 }
    ]
  }
}

使用计算属性排序

创建计算属性返回排序后的数组,原数组保持不变:

computed: {
  sortedItems() {
    return [...this.items].sort((a, b) => a.price - b.price)
  }
}

模板中直接使用sortedItems

<ul>
  <li v-for="item in sortedItems" :key="item.id">
    {{ item.name }} - {{ item.price }}
  </li>
</ul>

动态排序控制

添加排序控制参数实现动态排序方向切换:

vue实现排序

data() {
  return {
    sortKey: 'price',
    sortDirection: 1 // 1升序,-1降序
  }
},
computed: {
  sortedItems() {
    return [...this.items].sort((a, b) => {
      return (a[this.sortKey] > b[this.sortKey] ? 1 : -1) * this.sortDirection
    })
  }
}

添加排序控制按钮:

<button @click="sortDirection *= -1">切换排序方向</button>

多列排序

实现多字段排序逻辑,先按价格排序,价格相同再按名称排序:

vue实现排序

computed: {
  sortedItems() {
    return [...this.items].sort((a, b) => {
      if (a.price !== b.price) {
        return (a.price - b.price) * this.sortDirection
      }
      return a.name.localeCompare(b.name) * this.sortDirection
    })
  }
}

表格列排序

在表格列头实现点击排序功能:

methods: {
  sortBy(key) {
    if (this.sortKey === key) {
      this.sortDirection *= -1
    } else {
      this.sortKey = key
      this.sortDirection = 1
    }
  }
}

表格模板示例:

<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>

使用第三方库

对于复杂排序需求,可以使用lodash的orderBy函数:

import { orderBy } from 'lodash'

computed: {
  sortedItems() {
    return orderBy(
      this.items,
      [this.sortKey],
      [this.sortDirection === 1 ? 'asc' : 'desc']
    )
  }
}

标签: vue
分享给朋友:

相关文章

vue架构实现

vue架构实现

Vue 架构实现核心方案 Vue.js 的架构实现通常围绕模块化、组件化和状态管理展开。以下为常见实现方案: 基于单文件组件(SFC)的模块化 通过 .vue 文件组织模板、脚本和样式: <…

vue实现效果

vue实现效果

以下是Vue实现常见效果的几种典型方法,分为不同场景说明: 数据绑定与响应式更新 使用v-model实现表单双向绑定: <template> <input v-model="…

vue实现suspense

vue实现suspense

Vue 3 中实现 Suspense Suspense 是 Vue 3 引入的一个内置组件,用于处理异步依赖的加载状态。它允许在等待异步组件或异步数据加载时显示一个后备内容(fallback),直到异…

vue实现视频

vue实现视频

Vue 实现视频播放的方法 在 Vue 项目中实现视频播放可以通过多种方式完成,以下是几种常见的方法: 使用 HTML5 的 <video> 标签 在 Vue 组件中直接使用 HTML…

vue 简单实现

vue 简单实现

以下是 Vue 的简单实现示例,涵盖基础模板、数据绑定、方法及生命周期: 基础模板与数据绑定 <div id="app"> <p>{{ message }}</…

vue实现分步

vue实现分步

Vue 实现分步功能 在 Vue 中实现分步功能可以通过多种方式完成,以下是几种常见的方法: 使用动态组件 通过动态组件切换不同的步骤内容,结合 v-if 或 component 标签实现分步逻辑。…