javascript / expert
Snippet
BigInt Precision State Tracking with Custom Serializer
JavaScript BigInt primitive data types represent arbitrarily large integers. Standard JSON.stringify throws a TypeError on BigInt values, requiring a custom replacer function inside Vue computed properties.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
import { ref, computed } from 'vue';const rawBalance = ref(100000000000000000000n);export const safeJsonBalance = computed(() => {try {return JSON.stringify({ balance: rawBalance.value }, (_, value) =>typeof value === 'bigint' ? value.toString() + 'n' : value);} catch (err) {return JSON.stringify({ error: err.message });}});
vue
Breakdown
1
const rawBalance = ref(100000000000000000000n);
Initializes a Vue reactive ref wrapping a 64-bit BigInt primitive literal.
2
typeof value === 'bigint' ? value.toString() + 'n' : value
Replaces BigInt data types with strings during serialization to bypass JSON native serialization limits.
3
} catch (err) {
Catches potential serialization errors safely within the reactive computation flow.