Bringing in data from <script> to use in <script setup>

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.

Answer №1

Edit: it appears that the sequence is not important after all

any <script> will function normally

the content within <script setup> is transformed/compiled into a composition API "setup" function, and when that is invoked, all the top-level code in other <script> elements will have already been executed, hence idGen will be accessible

therefore

Disregard the remainder of this solution


Most vue3 examples using <script setup> alongside another <script> traditionally emphasize the order

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

In your scenario, this won't apply.

Yet, if the scripts are arranged in this manner

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

then

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

subsequently idGen will be accessible inside the <script setup>

Note: you can include as many <script> tags in your SFC as needed, regardless of their order, but only one <script setup>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to position an image in the middle of a Div

I am currently working with PHP and Smarty, attempting to display a slideshow's images in the center of a specific div, but I am encountering difficulties achieving this. Below you will find the code snippet. Can anyone help me figure out what I migh ...

How to retrieve the output of a nested function in Node.js

I have been attempting to retrieve a value from a function nested inside another function in my Node.js application, but it always seems to return undefined. var geo = { list: function(callback){ var returnval; gapi.getcodes(function(e ...

Interacting with an external Android library (Zebra) using Vue JS

I am fairly new to vue.js and currently working on integrating Zebra scanners' callback functionality into a Laravel + Jetstream project that uses Vue on the front-end. Our company utilizes Zebra scanners for stock movement, and I am tasked with brid ...

Issue with accessing form in Angular 6 Reactive forms for custom validator functionality

I am facing an issue with creating a password validation for reactive forms in Angular. Every time I try to verify the password, I get a “Cannot read property 'get' of undefined” error in the console. I have tried different methods to access ...

Tips for properly rendering contenteditable content in Laravel and Vue applications

I have successfully saved the content inside the #descrition section below. <div id="description" contenteditable="true"></div> The issue I am facing is that when I try to display it, it does not show in an HTML format. Instead, it displays e ...

Enable users to input their custom code and run it when the specified conditions are met

Currently, I am developing a Multi-tenant application that requires users to input their own code and run it under specific conditions. I have several ideas in mind, but I am unsure which approach would be most effective. All the proposed methods will ha ...

Is there a way to ensure that an AJAX request to a PHP file is synchronized with submitting form data to that same file?

My issue is that update.php is only able to retrieve the posted form data (post_edit). The variables sent earlier through AJAX are not being passed through. Notice: Undefined index: id_to_edit in ...\update.php on line 5 Notice: Undefined index: col ...

Having trouble with AngularJS not rendering on your HTML page?

This question has probably been asked countless times, but I'm genuinely unsure about what I'm doing wrong. The solutions I've come across so far haven't fixed the issue for me. Just to provide some context, I'm currently followin ...

Is it possible to display a value conditionally based on a condition from a Json object?

I'm looking to add a new feature that displays all the movies featuring Sean Connery in a button, but I'm stuck on how to implement it. Prettier 2.7.1 --parser babel </pre> Input: import React, { useState } from "react"; import ...

What steps do I need to follow to set up a Loading screen in Vue3 and Vite correctly?

Is there a better way to handle the loading state for an entire app instead of setting up a Loading screen with a time interval of 2 seconds using a Loading component? The Loading component has been directly integrated into the router-view of App.vue to a ...

Exporting a object in Angular2 Using TypeScript

I've been working on a small Angular2 application using Typescript and things have been going smoothly so far. My goal is to utilize a file called config that contains all the necessary settings for the application. Here's the file in question: ...

Displaying information on a chartJS by connecting to an API using axios in VueJS

Struggling with inputting data into a ChartJS line-chart instance. The chart only displays one point with the right data but an incorrect label (named 'label'): Check out the plot image The odd thing is, the extracted arrays appear to be accura ...

Pressing the escape key on the keyboard will act as a shortcut to go

Is there a way to use Javascript in a browser to make the escape key on the keyboard go back? For instance, when visiting this page and clicking the "Fullscreen" link, it would be great to simply press the escape key and return to the previous page. What ...

Toggle the backgroundImage visibility by setting it to either hidden or displayed using jquery

$('.arrow').css("background-image", "url('../img/arrow.png')").hide(); I have implemented a custom solution using CSS and jQuery to hide the downward arrow when scrolling down on my webpage. `$( document ).ready(function() {
 co ...

Create a pop-up window within a single controller using Angular.js

I followed a tutorial to create this code. I am interested in learning how to utilize just one controller for generating the dialog box. Currently, I am using two controllers for this project. Any guidance or tips would be greatly appreciated. View my cod ...

React component experiencing double execution of SetTimeout function

Every time I render the App component, the code inside setTimeout seems to be running twice. I've noticed that setTimeout executes after the call stack is cleared. I wonder if this has any connection to the issue. Could it be related to how React ha ...

Updating the value of a $scope variable located within an included template in AngularJS

My setup is quite simple as outlined below. The issue I'm facing is that out of the two variables I define within the $http success callback, only one is reflected in the UI. In this scenario, I am attempting to display progress when the controller l ...

Implement React-intl into the designated placeholder within the object

Currently facing an issue with the const inputProps in my code. I attempted to integrate React-intl into the react-autosuggest placeholder input, but now the placeholder text displays as: [Object object]. The getStepContent function is defined as follow ...

Adding the "input-invalid" class to the input doesn't take effect until I click outside of the input field

When the zipcode field is updated, an ajax call is made. If there are no zipcodes available, I want to mark it as invalid by adding the "input-invalid" class. However, the red border validation only appears when clicking outside of the input field. Is ther ...

The issue encountered during a POST request in Postman is a SyntaxError where a number is missing after the minus sign in a JSON object at position 1 (line 1

Running my API in a website application works flawlessly, but encountering SyntaxError when testing it in Postman - specifically "No number after minus sign in JSON at position 1" (line 1 column 2). The data is correctly inputted into the body of Postman a ...