Home > Net >  Importing result from <script> into <script setup>
Importing result from <script> into <script setup>

Time:06-04

I’m trying to enumerate the instances of a Vue component in order to ensure unique ids, and for that use a simple generator. Normally I would initiate the generator outside of the setup function:

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> sugar I’m not exactly sure how this is done. I know I can run side-effect in another <script> block which will only be executed once:

<script>
const idGen = generateIds("component:my-component");
</script>

However I don’t know I to access the shared idGen in my <script setup> to increment the enumerator and get the unique id.

<script setup>
// Where do I get idGen from the above <script>?
const id = idGen.next().value;
</script>

The only way I can think of to do this while using the <script setup> sugar is to initiate the generator in a separate file:

<script setup>
import { idGen } from "./id-generator.js";

const id = idGen.next().value;
</script>

The only problem is that it is a bit annoying to create a separate file just for this tiny logic which very much belongs with the component, so I would avoid it if I could.

CodePudding user response:

Edit: turns out the order is irrelevant after all

any <script> will run as normal

the code inside <script setup> is converted/compiled to a composition API "setup" function, and when that is called, all the top-level code in other <script> will have already executed, therefore idGen will already be available

so

Ignore the rest of this answer


Most vue3 <script setup> examples that use another <script> always show the order

<script setup></script>
<script></script>

In your case, this won't work.

However, if the scripts are in this order

<script>
const idGen = generateIds("component:my-component");
</script>

then

<script setup>
const id = idGen.next().value;
</script>

then idGen will be available inside the <script setup>

Note: you can have as many <script> tags in your SFC as you want, in any order, but only one <script setup>

  • Related