Search code examples
vue.jsvuejs3vuexvitevue-composition-api

Watch Vue 3 global variable for changes


I set a provider in my main.ts file:

app.provide('currentPage','test1')

And then inject it in a component Home.vue:

inject: ['currentPage'],

I then can update it and show it in that component without a problem using {{ currentPage }}.

But I want another component DeepNestedComponent.vue to be able to edit it, and Home.vue to be aware of the change.

When I inject the same provider in DeepNestedComponent.vue, I can edit and display in the component, but Home.vue is not aware of the change and {{ currentPage }} still display 'test1'.

How can I do that?


Solution

  • This pattern is designed only to pass some property from grandparent component to grandchild one, your case needs a shareable state based on Vuex or a composable function, let's build a solution based on the second approach :

    define the composable function :

    usePagination.ts

    import {  ref } from "vue";
    
    const currentPage=ref('test')
    
    export default function usePagination(){
    
      function setCurrentPage(val:string){
          currentPage.value=val;
     }
    
    return {currentPage, setCurrentPage}
    }
    
    

    DeepNestedComponent.vue

    import usePagination from './usePagination'
    ...
    setup(){
      const { setCurrentPage} =usePagination();
    
      // then use setCurrentPage to update the page
    
    }
    

    Home.vue :

    import usePagination from './usePagination'
    ...
    setup(){
      const { currentPage} =usePagination();
    
      // now you could receive the changes made in the other component.
      return {
           currentPage // expose it to the template 
       }
    }