Adjust the internal state within a Vue3 component using a window function

Creating a "Loader" component that is fully independent and functional just by being included in the layout requires exposing some methods for use. Here is the code I have come up with:

<script setup>
let active = false;

function show() {
    active = true;
}

function hide() {
    active = false;
}

window.loader = {show, hide};
</script>


<template>
    <Transition name="loader">
        <div class="loader" v-if="active">
        </div>
    </Transition>
</template>

<style scoped>
/* All styles and transitions */
.loader {
    position: fixed;
    height: 100vh;
    width: 100vw;
    background: #000;
    z-index: 9999;
    top: 0;
    left: 0;
    opacity: 0.5;
}
</style>

However, the show and hide methods do not update the internal state of the component as intended.

The goal is to include it in BaseLayout.vue like this:

<template>
  <div class="root">
    <Loader />

    <slot>All application body</slot>
  </div>
</template>

Is there a way to globally expose these functions and effectively change the internal state of the loader component? Are there any patterns or solutions to address this issue efficiently, considering its usage across multiple layouts?

Answer №1

To achieve this functionality, you can implement the following code:

<script setup>
import {ref} from 'vue'

let active = ref(false);

function displayLoader() {
    active.value = true;
}

function hideLoader() {
    active.value = false;
}

window.loader = {displayLoader, hideLoader, active};
</script>


<template>
    <Transition name="loader">
        <div class="loader" v-if="active">
        </div>
    </Transition>
</template>

<style scoped>
/* Styling and transitions for the loader */
.loader {
    position: fixed;
    height: 100vh;
    width: 100vw;
    background: #000;
    z-index: 9999;
    top: 0;
    left: 0;
    opacity: 0.5;
}
</style>

This implementation ensures that Vue detects changes accurately.

Answer №2

To create a composable function that can be accessed globally, define a function with a ref property outside the function and use its methods to change its state:

File: useLoader.js

import {ref} from 'vue';
const active = ref(false);

export default function useLoader() {
  function show() {
    active.value = true;
  }

  function hide() {
      active.value = false;
 }


return {active,hide,show}
}

In the loader component:

<script setup>
import useLoader from './useLoader'

const {active} =useLoader();
</script>


<template>
    <Transition name="loader">
        <div class="loader" v-if="active">
        </div>
    </Transition>
</template>

In another component:

<script setup>
import useLoader from './useLoader'

const {show,hide} =useLoader();
</script>
<template>
  <div class="root">
   <button @click="show">Show Loader</button>
    <Loader />

    <slot>All application body</slot>
  </div>
</template>

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

Mastering the art of customizing classes and styles in material-ui (React)

I am facing a challenge with version 1.2.1 of material-ui. My goal is to make the AppBar component transparent by overriding its styles as per the documentation here. This is the code snippet I have been working on: import React, { Component } from ' ...

The message of error is undetermined

Can someone help me with using the errorMessage object from routes in a partial? I have attempted to implement it as shown below: Route:- const express = require("express"); const router = express.Router(); const Character = require("../models/character" ...

Is there a way to efficiently import multiple Vue plugins in a loop without the need to manually type out each file individually?

I am looking for a way to streamline this code by using a loop to dynamically import all .js files from a specified directory (in this case, the 'plugins' directory). const plugins = ['AlertPlugin', 'AxiosPlugin', 'Confi ...

Looking for an API to retrieve random quotes and images from a website?

Greetings, my name is Antika. I recently embarked on a coding journey and have been focusing on learning HTML/CSS along with the basics of JS. Level of Expertise: Beginner During my exploration, I stumbled upon this intriguing website - . It stands out a ...

Replicate a click using jQuery to retrieve a filtered multigallery based on the URL

I have a website that was built using Elementor for a photographer. The site features an Elementor Multigallery with a filter at the top. I am looking to create external links that will direct users to specific subpages showing only filtered items. For ex ...

Displaying each character of text individually with jQuery

I am trying to display the text within a ul tag one by one when hovering over some text. However, I am encountering an error. How can I resolve this issue? You can view the code for mouseover functionality by hovering over the "hover here hover again" lin ...

Troubleshooting the issue with the default dropdown select in AngularJS

var jsonData ='[ {"type":"product", "id":1,"label":"Color", "placeholder":"Select Jean Color", "description":"", "defaultValue":"Brown", "choices":[{ "text":"Denim", "price":"$0.00", "isSel ...

Currently, I am expanding my knowledge of PHP and MySQL by working on a dynamic form that utilizes arrays. As I progress through the project,

One of my recent projects involved creating dynamic rows in a form using code. I managed to save the data in an array and display it using a foreach loop, but I'm facing challenges when trying to insert this data into a database. Here's a glimps ...

Tips for redirecting a page in React by forcing a route

Attempting to implement the guidance from this Stack Overflow solution on how to "go back home" after closing a Modal... import React, { Suspense, useState } from 'react'; import { BrowserRouter, Route, Switch, useHistory } from "react-route ...

Easily accessible jQuery tabs with the option to directly link to a specific tab

I currently have tabs set up on my webpage. The code for these tabs is as follows: $('ul#tabs li a').click(function(){ var id = $(this).attr('id'); var counter = 1; $("ul#tabs a.current").removeClass('cur ...

Mocking Ext.Ajax.request in ExtJS 4.2.1 is a process of em

When it comes to frontend unit testing using Jasmine, one of the challenges I faced was mocking all the requests in my application. Luckily, I have already tackled a method to mock all my proxies successfully: proxy: appname.classes.proxy.ProxyNegotiator ...

Backbone "recalling" stored data in attributes

Presented here is a basic model: myTestModel = Backbone.Model.extend({ defaults: { title: 'My Title', config: {}, active: 1, } }) While nothing particularly stands out, there is an interesting observation regardi ...

The $scope variable does not sync with the express API

I have noticed that the static part of my app is loading fine. Recently, I integrated a service using Express as a simple API. However, when I attempt to set the #scope from my module's controller, it seems like it hasn't loaded at all. I am puzz ...

Receiving a null value when attempting to access the ids of dynamically created HTML elements using JavaScript

Encountering issue with accessing ids of dynamically generated HTML elements using javascript In my current project, I am attempting to dynamically alter the ids of div elements and remove buttons that are appended to the parent div. The desired functiona ...

Display with organized information, Arrange with unprocessed data in DataTables.net

Below is a snippet of the datatables configuration I am working with: { "dom" : "rltip", "processing" : true, "serverSide" : false, "order" : [ [ 1 , "desc" ] ], "searching" : false, data: [ { "column-a" : "Samp ...

Retrieving pals from the API and showcasing them on the user interface

Currently, I am working on a project involving a unique Chat Application. While progressing with the development, I encountered an issue related to fetching friends data from the backend (node). Even though I can successfully retrieve the friends data in ...

Issues Encountered During Form Data Transmission via XHR

I require the ability to transfer files from one cloud service to another using Azure Functions running Node. In order to do this, I have installed the necessary packages (axios, form-data, xmlhttprequest) and am coding in VSCode. However, when dealing wi ...

Unit testing for changes in AngularJS $scope variables within the .then() function

I'm currently facing an issue with unit testing a function in my controller. The problem lies in making a $scope variable testable. I am assigning the variable within the .then() block of my controller and need to ensure it is set correctly when the . ...

JEST does not include support for document.addEventListener

I have incorporated JEST into my testing process for my script. However, I have noticed that the coverage status does not include instance.init(). const instance = new RecommendCards(); document.addEventListener('DOMContentLoaded', () => ...

Combining package.json commands for launching both an Express server and a Vue app

I recently developed an application using Vue.js and express.js. As of now, I find myself having to open two separate terminal windows in order to run npm run serve in one and npm start in the other. My ultimate goal is to streamline this process and have ...