Introducing the new Vue loading component - a sleek

Exploring the idea of adding loading functionality to a component has led me to consider different approaches.

Initially, I thought about creating a Higher-Order Component (HOC) that would handle the loading state and text while preventing click events from passing through. The structure I envisioned looked like this:

<loading-hoc :active="loading">
    <my-component></my-component>
</loading-hoc>

Upon implementing this solution, I noticed in the Vue dev tools the following representation:

https://i.sstatic.net/urUNW.png

Further exploration led me to ElementUI's approach, which involves using a directive to incorporate a DOM element into the current component. This implementation can be viewed here.

Question:

What are the advantages and disadvantages of each method? Is there a preferred way to achieve this?

From my perspective:

a) Utilizing a HOC:

  • Results in a verbose tree displayed in dev tools (negative)

b) Implementing a directive

  • Adds DOM nodes from outside the component (negative)

Answer №1

To make things easier, you can start by adding a property named "loading" with the value of true to the data object. This property will be used to control the visibility of the loading element through the use of v-if.

Here's a simple demonstration:

<div id="app">
    <div v-if="loading" class="loading">Loading...</div>

    <h5>{{content}}</h5>
</div>

script

new Vue({
    el: '#app',
    data:{
        content: null,
        loading: true
    },
    mounted(){
        setTimeout(() => {
            this.content= 'Data fetched from external server or database';
            this.loading = false;
        },3000);

        //If you are using a data fetching API like axios, set the loading to false in the success callback handler

        axios.get('/api').then( data => {
            console.log(data);
            this.loading = false;
        });
    }
}) 

Check out the demo on this fiddle link

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

Sending API Requests to External Services Using Node.js

I have created a Node console application. Within the app, I am attempting to send data to a third-party web service. Interestingly, I can successfully add data using the third-party service through POSTMAN. The setup of my request in Postman looks like th ...

Navigating the world of date pickers: a deceptively easy challenge

Take a look at this fiddle example to get started: http://jsfiddle.net/1ezos4ho/8/ The main goals are: When a date is selected, it should be dynamically added as the input value, like <input type text value="date selected".... Update: <s ...

The translation feature in vue-i18n is failing to translate when used with the values attribute

I'm currently working on importing a .json file for translation purposes. <template> <template v-slot:footer> <div>{{ $t('menu.file.new.label', $i18n.locale, locale) }}</div> <--Issue outputs menu.file.n ...

Incorporating Vue.js components into PHP applications

I am currently working on a project using PHP in conjunction with Vue.js and vue-router. In my PHP form handler, I have implemented functionality to send emails. What I am trying to achieve is redirecting the user to a specific component within my Vue ap ...

Steps to modify a button's color once all mandatory fields have been completed

Hey there! I've been working on some code in vue.js and I've implemented field validation. I'm looking to change the button color once all input fields are completely filled out. Additionally, if a user tries to submit the form without filli ...

Emulate a keyboard key press in the active HTML input field by clicking on an on-screen element without changing the input focus

In my web apps, I am using mobile devices equipped with barcode scanners to interact with ASP.NET web form applications. The catch is that these devices only have a numeric hardware keyboard and do not include any letters. However, users need the ability t ...

Using footable js will eliminate all form elements within the table

After incorporating the Footable jQuery library to create a responsive table, I encountered an issue with input tags and select boxes being removed by the Footable JavaScript. It turns all these tags into empty <td> elements. <table id="accordi ...

How can I make the default value change upon loading the page using jQuery?

I have set up an onchange method for a select box in my project. It is currently functioning as intended, showing and hiding a div based on the selected option. However, I am facing an issue where the show and hide functionality does not work for the def ...

Unsuccessful attempts to animate with Jquery in Google Chrome are persisting

I've been facing a challenge with my jquery code that seems to be getting the "click" function but does not animate. Instead, it just abruptly jumps without any smooth animation. I've spent hours trying to troubleshoot this issue. Here is the Jq ...

The final input is the only one that functions

I am currently working on a large form, but I am encountering a major issue with it. In certain sections of the form, only the last input field seems to be functional. For example: [...] <div class="main_data"> <span class="info">main dat ...

Does $state.go trigger relevant events when transitioning to the current state?

Imagine I am currently in state A, and within this state there is a button with an ng-click event handler like this: $scope.go = function() { $state.go("A"); } My query is whether the events $stateChangeStart and $stateChangeSuccess are triggered? ...

Arranging JSON object in Javascript based on date (String)

I am currently working with a JSON object in JavaScript and my goal is to arrange the object based on dates in ascending order. fileListObj[id] = date; output : "#HIDDEN ID": "16/12/2013" What steps should I take to sort the object by the most recent d ...

Auto-filling a form with the selected 'id' in Django using JavaScript or AJAX

I am a novice and I want the form to be autofilled when I select a vehicle ID from the template. Here are my models. class Fuel(models.Model): vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE) previous_km = models.IntegerField(blank=False, nul ...

What is the process of naming a component in the setup tag of Vue3?

Within the export default {} approach, there is a name property used to specify the component name for Vue Devtools. However, what would be the equivalent in the new <script setup> syntax? https://i.sstatic.net/M9Q8x.png ...

Ways to view the outcome of json_encode function?

In PHP, I have an array that looks like this: $user_data = Array ( [session_id] => 30a6cf574ebbdb11154ff134f6ccf4ea [ip_address] => 127.0.0.1 [user_agent] => Mozilla/5.0 (Windows NT 5.1; rv:9.0.1) Gecko/20100101 Firefox/9.0.1 [las ...

Loading screen featuring symbol percentage

https://i.sstatic.net/Ksogp.jpg How can I create a loading panel that includes a percentage symbol? I have searched for solutions but most of them suggest using a spinner. However, I specifically need a panel with the % symbol included. Is it possible to ...

Attempting to trigger an action from a Vuex module proves futile as the error message "[vuex] unknown action type" is generated

I've been struggling to successfully register a Vuex module. Below is the code I've been working with: stores/index.js: import Vuex from 'vuex'; import resourcesModule from './resources'; import axios from '@/helpers/ax ...

How can I match the date format of d-M-Y using JavaScript regex?

When it comes to date formatting in PHP, I typically use the format d-M-Y. Recently, I attempted to match these dates using a JavaScript regex: s.match(new RegExp(/^(\d{1,2})(\-)(\w{3})(\-)(\d{4})$/)) I wanted to use this regex w ...

Step-by-step guide on adding data to an arraylist using JavaScript

My ajax callback function receives a json object (arraylist parsed into json in another servlet) as a response, and then iterates through it. Ajax section: $.ajax({ url:'ServiceToFetchDocType', data: {" ...

What could be causing my reducer function to return 'NaN'?

I have been working on updating the total quantity in my shopping cart. Utilizing hooks useSelector, I retrieve the state from Redux and access all the items currently in my cart. By using reduce function, I am able to calculate the total quantity of items ...