解决Vue处理超过16位数字精度丢失问题

发布时间 2023-12-06 13:46:20作者: 会转圈圈的哆瑞米

当我们使用MyBatis-Plus 使用 ID_WORKER 或者 ASSIGN_ID(雪花算法) 生成的id作为主键时,因为其长度,为19位,而前端一般能处理16位,如果不处理的话在前端会造成精度丢失,最后两位会变成00,如下图,感觉像是四舍五入后的效果。

 

处理这种问题有两种方案,要么后端出处理,要么前端处理

后端处理:

直接把id类型改为String就行,这样是可以,但是我们如果非要用Long呢?

我们可以给对应的实体类主键属性加入注解@JsonSerialize

import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;

@JsonSerialize(using = ToStringSerializer.class)
@TableId
private Long id;

前端处理:

前端一般都是用axios进行数据请求,我们通过引入json-bigint来解决

yarn add json-bigint
//
npm install json-bigint

在封装的请求工具类中添加如下代码即可。

axios.defaults.transformResponse = [
  function (data) {
    const json = JSONBIG({
      storeAsString: true
    })
    const res = json.parse(data)
    return res
  }
]