You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vuesax数据表格datetime日期列无法实现切换排序问题求助

问题根因

Vuesax 表格的排序逻辑完全依赖 <vs-td> 组件绑定的 data 属性值,你当前给日期列绑定的是 formattedDateTime 方法返回的 DD/MM/YYYY 格式字符串,排序时会按字符串字典序处理,因此无法按照时间实际先后顺序排序。

解决方案

仅需调整日期列的 data 属性绑定逻辑,将原始时间值传给排序底层,展示层保留格式化逻辑即可,修改后代码如下:

<template>
    <div>
        <vs-table search :data="users">
            <template slot="thead">
                <vs-th sort-key="name">
                    Full Name
                </vs-th>
                <vs-th sort-key="email">
                    Email
                </vs-th>
                <vs-th sort-key="last_login">
                    Last Logged-in
                </vs-th>
            </template>

            <template slot-scope="{data}">
                <vs-tr 
                    :key='index'
                    v-for='(user, index) in data'
                >
                    <vs-td :data="user.name">
                        {{user.name}}
                    </vs-td>
                    <vs-td :data="user.email">
                        {{user.email}}
                    </vs-td>
                    <!-- 仅修改此处:data绑定原始时间值,展示仍用格式化后内容 -->
                    <vs-td :data="user.last_login">
                        {{formattedDateTime(user.last_login)}}
                    </vs-td>
                </vs-tr>
            </template>
        </vs-table>
    </div>
</template>

<script>
import moment from 'moment'
        
export default {
    methods: {
        formattedDateTime(dateTime) {
            return dateTime ? moment(String(dateTime)).format('DD/MM/YYYY hh:mm A') : "N/A";
        }
    }
}
</script>

如果你的原始last_login是字符串格式的时间值,Vuesax仍无法正确识别排序,可以给<vs-table>添加自定义排序方法:

  1. 表格标签添加属性:<vs-table search :data="users" :sort-method="customSort">
  2. 新增排序方法:
methods: {
    customSort(a, b, sortKey) {
        if (sortKey === 'last_login') {
            // 空值排在后面
            if (!a.last_login) return 1
            if (!b.last_login) return -1
            // 转成时间戳比较
            return new Date(a.last_login).getTime() - new Date(b.last_login).getTime()
        }
        // 其他列走默认字符串排序
        return a[sortKey].toString().localeCompare(b[sortKey].toString())
    },
    // 原有格式化方法保留
    formattedDateTime(dateTime) {
        return dateTime ? moment(String(dateTime)).format('DD/MM/YYYY hh:mm A') : "N/A";
    }
}

内容的提问来源于stack exchange,提问作者moin205

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 05:24:04