To ensure unique ids for instances of a Vue component, I am using a simple generator to enumerate them. Typically, I would initialize the generator outside of the setup
function like this:
const idGen = generateIds("component:my-component");
export default {
setup() {
const id = idGen.next().value;
return {
id, // e.g. "component:my-component/0042"
};
},
};
However, with the <script setup>
syntax, I am unsure of how to achieve this. I understand that I can perform side-effects in another <script>
block that will be executed only once:
<script>
const idGen = generateIds("component:my-component");
</script>
But I am uncertain about accessing the shared idGen
in my <script setup>
to increment the enumerator and obtain the unique id.
<script setup>
// How do I access idGen from the previous <script> block?
const id = idGen.next().value;
</script>
The solution I have come up with while utilizing the <script setup>
functionality is to initialize the generator in a separate file:
<script setup>
import { idGen } from "./id-generator.js";
const id = idGen.next().value;
</script>
Although effective, it feels cumbersome to create a separate file solely for this small piece of logic that is closely related to the component. I would prefer to avoid this if possible.