Home > other >  How to update global var in all components
How to update global var in all components

Time:07-14

I would like to be able to set up an automatic page title change system according to my loaded view.

First thought of using a global variable since the main.js :

// MAIN.JS FILE
const App = createApp(AppVue).use(router)

App.config.globalProperties.$myGlobalVariable = "test"

App.mount('#app');

But, when I change the value in my component, it remains only local to this one

// VIEW1.VUE
created() {
    this.$myGlobalVariable = "Compte utilisateur"
    console.log(this.$myGlobalVariable);
    // show "Compte utilisateur"
}

// VIEW2.VUE
created() {
    console.log(this.$myGlobalVariable);
    // show "test"
}

CodePudding user response:

You can use a reactive state in a composable.

const title = ref(''); // <=== outside of function scope

export function useTitle() {
  const setTitle = (newTitle) => {
    title.value = newTitle;
  };

  return { title, setTitle };
}

You can use it by title or update it by setTitle in any component.

For more resources.

https://vuejs.org/guide/reusability/composables.html

  • Related