Create a Vue application that utilizes a promise to display content and then waits for user input

Seeking guidance for a design query, I am dealing with a JavaScript script that is heavy on logic. It is structured using promises as shown below:

init()
    .then(result => doSomethingA(result)) 
    .then(result => doSomethingB(result))
    .then(result => loadVueApp(result))

The loadVueApp() function trigger the following actions:

new Vue({
  el : '#app',
  render : h => h(App)
});

This code renders the Vue app, allowing user interaction to navigate screens and make selections stored in a global EventBus type component.

My question pertains to passing user choices back to the tower of promises. Is this necessary, and if so, how should it be handled?

One approach is to resolve the loadVueApp immediately upon the app's appearance, then later initiate a function call back to the script containing heavy logic - although this method lacks elegance.

Any insights or suggestions would be appreciated.

Thank you in advance.

Answer №1

Below is a straightforward demonstration that showcases the following:

  • The Vue component is created from a template and added to the <body> element instead of an existing DOM element (useful if you want to hide the UI initially).
  • The promise only resolves with the entered text when the submit button is pressed. The component instance is then destroyed and taken out of the DOM.

const InputUI = {
  template: '#input-ui',
  data() {
    return {
      value: '',
    };
  },
};

function getInput() {
  return new Promise(resolve => {
    const inputUI = new Vue(InputUI);
    
    inputUI.$once('submit', value => {
      inputUI.$destroy();
      inputUI.$el.remove();
      resolve(value);
    });
    
    inputUI.$mount();
    document.body.appendChild(inputUI.$el);
  });
}

getInput().then(value => alert(value));
<script src="https://rawgit.com/vuejs/vue/dev/dist/vue.js"></script>

<template id="input-ui">
  <div>
    <input v-model="value">
    <button @click="$emit('submit', value)">Submit</button>
  </div>
</template>

If utilizing single file components, your code structure would resemble something like this:

InputUI.vue

<template>
  <div>
    <input v-model="value">
    <button @click="$emit('submit', value)">Submit</button>
  </div>
</template>

<script>

export default {
  data() {
    return {
      value: '',
    };
  },
};

</script>

main.js

import Vue from 'vue';
import InputUI from './InputUI.vue';

function getInput() {
  return new Promise(resolve => {
    const InputUIVue = Vue.extend(InputUI);
    const inputUI = new InputUIVue();

    inputUI.$once('submit', value => {
      inputUI.$destroy();
      inputUI.$el.remove();
      resolve(value);
    });

    inputUI.$mount();
    document.body.appendChild(inputUI.$el);
  });
}

getInput().then(value => alert(value));

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

Troubleshooting: GSAP Scrolltrigger malfunctions when using multiple triggers

Having multiple triggers with different functionalities: Show or remove a canvas Change the background color of a section Play or pause video when in view Play or pause CSS animation The first two triggers work fine individually, but I am encountering an ...

What is the most effective method for implementing COPY/INSERT functionality with cascading effects in PostgreSQL?

Seeking advice on the most effective method to perform an "on cascade copy/insert" of linked elements within PostgreSQL. To better explain my scenario, I've crafted a straightforward example: Understanding the Database Structure Within the datab ...

What is the best way to maintain the position of components (such as a Card component) when one is expanded in a Material-UI and ReactJS project

Currently, I am working with an expandable Card component from Material-UI and using flex for aligning the components. However, when one card expands, it affects the positioning of the other components in the row: https://i.stack.imgur.com/vGxBU.png What ...

What is the best way to handle the rows that have been checked in the table?

Imagine you have the given table structure: <table> <thead> <tr> <th>Column 1</th> <th>Column 2</th> <th>Column 3</th> </tr> </thead> <tbody> <t ...

Differences between Vue.js Composition API and Options API - utilizing posts ref within a v-for iteration

I am relatively new to working with VueJS, and I am facing a challenge that has me stumped. On a page that fetches data using axios from my posts on a wordpress site: export default { data() { return { postsUrl: "https://localhost/wordpre ...

Stopping the execution of code in Node.js after returning a JSON response

When a user is not found, the code still continues executing after sending the JSON response. The JSON response is generated in a separate class and returned from there. var user = new UserClass(obj, null); var userObj = user.getUser(res, req, 'user ...

Challenges with loading times in extensive AngularJS applications

We are currently tackling performance issues related to the loading time of our AngularJS application. The page takes a significant amount of time to load, and we are exploring potential causes for this delay. One factor that could be contributing to the ...

What sets apart genuine user interactions from programmatically generated actions?

Working with webkit notifications on Chrome has presented a challenge. The window.webkitNotifications.requestPermission method must be called from a user action, such as a click. Attempting to call it at any other time will not have any effect and will not ...

Displaying live data from an XMLHttpRequest in a Vue component in real-time

I'm currently working on implementing lazy loading for a list of posts fetched from the WordPress REST API. My goal is to load additional news stories upon clicking an HTML element. However, I'm facing issues with accessing the original Vue inst ...

How do I navigate back to show the initial parent component instead of the nested child component in ReactJS?

The data flow in my React app goes like this: SubmitForm -parent-> Results -parent-> Presentation -parent-> ButtonBackToSearch I am delving into ReactJS and trying to adopt the right mindset for creating single-page applications. Currently, I am ...

Retrieving visual information from Google Street View entity

Looking for a solution to extract imagery from the Google Street View panorama within a web page? In my program, I navigate specific routes using Google Street View's javascript API controlled by an embedded Java applet on the same page. I am seeking ...

Angular Component - Array missing initial value in @Input property

Having trouble transferring values between components? I'm currently dealing with a situation involving two components: report-form and comment-form. The report form contains an array of comments, displaying a list of comments and a button for each on ...

Loop through the tabs array and display varying views based on conditionals

I am currently working on building tabs and tab panels iteratively to display information, but I am facing issues in getting the desired output. For each name in a list, I need to create a tab and a corresponding tab panel underneath it. For example, the ...

Transferring information from a Jade file to a Node.js server

I'm currently working on creating a data object within my Jade view page that will be used in my server-side JS. The data object involves dynamic HTML generation that inserts input boxes based on user input. function addDetail() { var det ...

Why is it that in IE9, submitting a basic form using jQuery doesn't seem to work?

Take a look at the code snippet below: <html> <head> <style type="text/css"> #myform {display:none;} </style> </head> <body> <button type="button" id="uploadbutton">Upload Images</button> <form name="myf ...

Overlapping Divs - HTML Elements Crossing Paths

My challenge is to position the Social Icons at the bottom of the screen and align the Image Gallery in the middle. However, the social Icons keep moving to the center of the screen and the Image gallery ends up overlapping them, making it difficult for me ...

Toggling jQuery to show or hide content depending on the selector

I am looking to implement a jQuery-based animation and here is the code I have so far: >items=document.querySelectorAll("#customers td span"); [<span alt=​" 02,Counter,11,2013-04-06 14:​59:​16">​ 02​</span>​, <span>​11 ...

The jQuery AJAX post request with JSON data may not include a post body when sending to specific URLs

I've been scratching my head over this issue for quite some time. The ajax request in question looks like this: $.ajax({ url: UPDATE_USER_INFO_URL , type: "POST", dataType: "json", contentType: "application/json", data: JSON.strin ...

When the parent div contains at least four divs, show the scroll arrow containers

In my code, there is a parent div that holds multiple child divs. If the number of child divs within the parent div exceeds 4, I want to show the scroll arrow containers. If it's less than 4, then those arrow containers should not be displayed. The ...

JQuery - Issue with setTimeout Function on Mouseleave Event

I am currently facing an issue with the script below. The goal is to display a div instantly when hovering over a specific area, and then make it disappear after a certain amount of time when leaving that area. Everything works perfectly, except if the mou ...