0

I have another js file that stores data like users.

export var selectedUser = null;

(the variable changes multiple times)

However, when I try accessing that data from App.vue file, it says it hasn't changed.

Here's how I'm importing the data:

import * as config from "./config"
  • Its not global. It is its own copy every time you include it. If you want global variables use this https://stackoverflow.com/questions/37367588/what-is-the-best-way-to-declare-global-variable-in-vue-js – John Apr 10 '21 at 16:39
  • you have updated the variable like config. selectedUser= data, right? so the config related data is not accessible in another page scope. so you have to add your data into global scope – Mahamudul Hasan Apr 10 '21 at 16:40

2 Answers2

0

If you import a regular JS file, it will not be reactive because regular JS do not have the VueJS state wired to it, hence it will not be reactive.

Why do you not add the state directly into VueJS ? Or even use Vuex.

kissu
  • 40,416
  • 14
  • 65
  • 133
0

You can make it reactive by creating a function to set selected user from the JavaScript file and return callback function if user selected and listen to callback in vuejs component to update the selectedUser variable (the variable will be in vuejs component)

Component code :

<template>
  <div>
    user {{ selectedUser }}

    <button @click="update()"> Update user </button>
    
  </div>
</template>

<script>
import getUserData from './GetUser';
import updateUser from './UpdateUser';

import {ref} from 'vue'
export default {
  name: 'HelloWorld',

  setup(){
    let selectedUser = ref('ahmed');
    const userData = getUserData();

    function update(){
      updateUser(selectedUser, (theNewValue) => {
        // to be reactive
        selectedUser.value = theNewValue;
      });
    }
    return {...userData, update, selectedUser};

  }

}

User file :

export default function updateUser(selectedUser, updated){
    selectedUser = 'new value';
    alert(`User Updated Successfully ${selectedUser}`);
    // pass new value to get it from vuejs component
    updated(selectedUser)
}
Debug Diva
  • 26,058
  • 13
  • 70
  • 123