Skip to content

Commit

Permalink
fix: made GUID and number id composables non-reliant on useId
Browse files Browse the repository at this point in the history
  • Loading branch information
Simon Milfred committed Jun 10, 2024
1 parent 888f1a7 commit bcfbe06
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 14 deletions.
2 changes: 2 additions & 0 deletions .playground/pages/[...slug].vue
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
const route = useRoute();
const layout = 'default';
console.log(useGUID(), useNumberId());
definePageMeta({
layout: false,
key: (route) => route.path,
Expand Down
27 changes: 15 additions & 12 deletions composables/useGUID.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
/* Create a GUID */
function useGUID(key = useId()) {
return useState('_guid-' + key, () => {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(
/[xy]/g,
function (c) {
const r = (Math.random() * 16) | 0,
v = c == 'x' ? r : (r & 0x3) | 0x8;
return v.toString(16);
}
);
}).value;
/* Make a GUID */
function useGUID(key) {
return key ? useState('_guid-' + key, makeGUID).value : makeGUID();
}

export default useGUID;

function makeGUID() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(
/[xy]/g,
function (c) {
const r = (Math.random() * 16) | 0,
v = c == 'x' ? r : (r & 0x3) | 0x8;
return v.toString(16);
}
);
}
8 changes: 6 additions & 2 deletions composables/useNumberId.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
/* Create a number ID (unlike useId() which generates an id usable by the DOM) */
function useNumberId(key = useId()) {
function useNumberId(key) {
const counter = useState(() => 0);
return useState('_num-id-' + key, () => counter.value++).value;
return key ? useState('_num-id-' + key, nextNumber).value : nextNumber();

function nextNumber() {
return counter.value++;
}
}
export default useNumberId;

0 comments on commit bcfbe06

Please sign in to comment.