[Vuejs]-Change local state from window function in Vue3

2๐Ÿ‘

โœ…

You can do something like :

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

let active = ref(false);

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

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

window.loader = {show, hide, active};
</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>

it will allow vue to detect changes correctly

๐Ÿ‘คLk77

1๐Ÿ‘

Define a composable function with ref property outside the function in order to be global, and use that methods to change its state :

useLoader.js

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

export default 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 other 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>

Leave a comment