Using the `setTimeout` function to swap components

As I work on implementing a setTimeout method, the goal is to trigger an event after a .5 second delay when one of the three buttons (drip, french press, Aeropress) is pressed. This event will replace {{ShowText}} with {{ShowText2}}, which will display 'waiting for ' + this.order_type.


    <div id="app">
        <barista-template></barista-template>
    </div>

    <!--template for customer-->
    <script type="text/x-template" id="b-template">
        <div>
            <div>{{showText}}</div>
            <button v-on:click="choose('drip')">Drip</button>
            <button v-on:click="choose('frenchpress')">French Press</button>
            <button v-on:click="choose('aeropress')">Aeropress</button>
            <div>{{showText2}}</div>
        </div>
    </script>

    <script type="text/x-template" id="c-template">
        <div>
            <div>{{showText2}}</div>
        </div>
    </script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.4/vue.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.19.1/TweenMax.min.js"></script>
    <script src="JS/app.js"></script>

______________JS_______________________________


    Vue.component("barista-template",{
        template: "#b-template",
        data: function () {
            return{
                order_type:"",
                order_value: "",
            }
        },
        computed: {
            showText () {
                if(this.order_type === '') return '';
                return 'One ' + this.order_type + ' that would be ' + this.order_value
            },
            methods: {
                swapComponent: function(component)
                {
                    setTimeout(() => {
                        this.showText2('brewing')
                    }, 1500);
                    this.currentComponent = component;
                }
            }
            showText2 (){
                if(this.order_type === '') return '';
                return 'waiting for ' + this.order_type
            }
        },
        methods: {
            choose: function (order_type) {
                this.order_type = order_type;

                if (this.order_type == "drip") {
                    this.order_value = "$10";
                }
                if (this.order_type == "frenchpress") {
                    this.order_value = "$20";
                }
                if (this.order_type == "aeropress") {
                    this.order_value = "$30";
                }
            }
        },
    });
    new Vue ({
        el:"#app",
        data:function () {
            return{
                showing:true
            }
        }
    });

Answer №1

Do you approve of this behavior? I introduced a variable called swapping to indicate when there is swapping happening (which means showText2 is displayed).

swapComponent sets the value of swapping to true, then uses setTimeout to set it back to false. The function choose calls swapComponent.

Vue.component("barista-template", {
  template: "#b-template",
  data: function() {
    return {
      order_type: "",
      order_value: "",
      swapping: false
    }
  },
  computed: {
    showText() {
      if (this.order_type === '') return '';
      return 'One ' + this.order_type + ' that would be ' + this.order_value
    },
    showText2() {
      if (this.order_type === '') return '';
      return 'waiting for ' + this.order_type
    }
  },
  methods: {
    swapComponent: function() {
      this.swapping = true;
      setTimeout(() => {
        this.swapping = false;
      }, 1500);
    },
    choose: function(order_type) {
      this.swapComponent();
      this.order_type = order_type;

      if (this.order_type == "drip") {
        this.order_value = "$10";
      }
      if (this.order_type == "frenchpress") {
        this.order_value = "$20";
      }
      if (this.order_type == "aeropress") {
        this.order_value = "$30";
      }
    }
  }
});
new Vue({
  el: "#app",
  data: function() {
    return {
      showing: true
    }
  }
});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
<div id="app">
  <barista-template></barista-template>
</div>

<!--template for customer-->
<script type="text/x-template" id="b-template">
  <div>
    <div>{{swapping ? showText2 : showText}}</div>
    <button v-on:click="choose('drip')">Drip</button>
    <button v-on:click="choose('frenchpress')">French Press</button>
    <button v-on:click="choose('aeropress')">Aeropress</button>
  </div>
</script>

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

Find the total duration of all items within an array by utilizing the Moment.js library

Within an array of objects, each object contains a field named "duration" that represents a string. Here is an example of one such object: { id: 14070 project: {id: 87, name: "Test project for time tracking"} issue: {id: 10940} user: {id ...

The script ceased functioning immediately following the inclusion of a case-insensitive search feature and interactive images

In the process of creating my inaugural project featuring a collection of images, I wanted to include a filter/search bar at the top. This bar would dynamically filter the displayed pictures based on user input. For example, typing "Aatrox" into the search ...

Go to a distant web page, complete the form, and send it in

As the creator of Gearsbook.net, a social network for Gears of War players, I am constantly striving to improve the site's functionality. Currently, it is quite basic and in need of updates. One highly requested feature by users is the ability to lin ...

discovering obscured information using jquery

I am working on a code snippet where I need to hide the detailed content for display purposes and only show it during printing: <div> <ul> <li> <span style="font-size: 1.25em;"> <strong> ...

Ways to Export HTML to Document without any borders or colorful text

How can I make a contentEditable area visible when filling text and then disappear when exporting the document? I found a script online that allows you to do this, but the issue is that the contentEditable area is not visible until clicked on. To address t ...

Tips on obtaining the element selector when a div is being dynamically loaded during an AJAX call

When running two ajax calls, I encounter an issue where the second call loads some HTML onto the page that is needed for processing a specific div in the first call. However, since the div is not present until after the second call is completed, I receiv ...

An error has occurred in React with a nested JSON object, suggesting that it may actually

I encountered an interesting error with my React file using Axios. While the data retrieval from my post works fine, I am facing a problem when trying to display all posts on one page. Despite my efforts to find a solution, I have not been successful. Bel ...

Is there an XML File Wrapper to Generate PDF Output?

Greetings Forum Members, I have been given the responsibility of creating a PDF file from multiple XML files. Has anyone come across an XML wrapper file before? This type of file would essentially contain a list of all the source XML file names in a spec ...

Angular 7: Finding the variance between array elements

How can I subtract the values from the first 3 rows of the table? The formula is TVA Collectée - TVA Déductible - TVA Déductible/immo If the result is positive, it should be displayed in the box labeled TVA à Payer. If it's negative, it should g ...

A simple method in JavaScript/TypeScript for converting abbreviations of strings into user-friendly versions for display

Let's say I am receiving data from my backend which can be one of the following: A, B, C, D Although there are actually 20 letters that could be received, and I always know it will be one of these specific letters. For example, I would like to map A ...

Having trouble utilizing the DatePicker component in my react native application

I've encountered an issue while using DatePicker in react native. Whenever I try to use it, an error pops up saying: "render error a date or time must be specified as value prop". Here is the link to my repository: my github repository const [date, se ...

Understanding Joi validation - setting a field as optional depending on the input received

I have been struggling to integrate the following joi validation. joiSchema = Joi.object().keys({ taskno: Joi.string().alphanum().required().uppercase().trim(), taskstatus: Joi.valid('G', 'C', 'I', 'S'), ...

The express js backend (mongodb) is returning {error:{ }}

I'm learning how to POST Data to a Mongo DB using Express.js. Recently, I picked up Express.js for backend server development and this is my app.js const express = require("express"); const mongoose = require("mongoose"); require("dotenv/config") con ...

Matching regex only on complete strings, not on parts of strings

My goal is to dynamically add and remove strings to a textarea when values in a table are clicked. The functionality should allow users to select and deselect values in the table, with the selected values adding or removing themselves from the textarea. It ...

Guide on entering text into a concealed text box using WebDriver and Java

When attempting to use sendkeys on an input field, I encountered a warning that puzzled me: org.openqa.selenium.InvalidElementStateException: Element must not be hidden, disabled or read-only (WARNING: The server did not provide any stacktrace informati ...

Encountering this error message while attempting to synchronize an Ionic Angular project in Xcode using npx cap sync

Every time I try to run npx cap sync on my Ionic Angular project in Xcode, I encounter the following error. [!] The plist file at path `/Users/user/Documents/GitHub/project-name/ios/App/App.xcodeproj/project.pbxproj` doesn't exist. I face the ...

Enclose each instance of "Rs." with <span class="someClass">

I'm facing an issue with the currency symbol "Rs." appearing in multiple places on my website. I want to enclose every instance of this text within <span class="WebRupee">. However, if it's already wrapped in <span class="WebRupee">, ...

Utilize React Native to showcase JSON data in a visually appealing way by organizing it into titles and corresponding lists for both

I created a live code on Expo.io to showcase JSON data categories as titles and the subs as a list. This code utilizes .map() to retrieve data from an array. import React, { useState } from 'react'; import { Text, View, StyleSheet, Button, FlatLi ...

Can you extract information from the XML file and modify the anchor tags?

<description> <div class="field field-name-field-image field-type-image field-label- hidden"><div class="field- items"><div class="field-item even"><a href="/news/news/vg"> ...

Has Angular been assimilated into the window object by webpack?

I'm encountering a puzzling issue with webpack that I can't seem to resolve. Here is the link to my webpack.config file: https://github.com/saike/maluvich-browser/blob/master/webpack.config.babel.js In my project, I import angular using ES6 mo ...