Search code examples
vue.jsvuejs3vue-composition-api

How do I track data changes in external file with composition APi in Vue 3


I have a vue which I'm importing from another file however I'm having trouble getting vue to track when the data changes here my code

System.JS

export let loggedIn = false;

App.vue

<template>
  <div v-if="loginStatus"> ...
</template>

<script>
import { loggedIn } from "./snippets/system";
export default {
  setup() {
    init();
    let loginStatus = ref(loggedIn);    

    watch(loggedIn, (currentValue) => {
        loginStatus.value = currentValue;
        ...
    });

    return {    
      loginStatus      
    };
  },
};
</script>

Solution

  • You should create composable:

    system.js

    export function useSystem() {
      const loginStatus = ref(false);
    
      return {
        loginStatus
      }  
    }
    

    App.vue

    <template>
      <div v-if="loginStatus"> ...
    </template>
    
    <script>
    import { useSystem } from "./system.js";
    
    export default {
      setup() {
        init();
        const { loginStatus } = useSystem();
    
        watch(loginStatus, (currentValue) => {
            ...
        });
    
        return {    
          loginStatus      
        };
      },
    };
    </script>