0

I'm trying to have a shared store of global variables in a Vue.js application. Since only some properties are relevant to the state of the actual application, only those are wrapped in a Vue reactivity Ref object. However, those that are not wrapped by a Ref do not have consistent values across different contexts/scopes. Here's example code that represents what I'm trying to do:

Store.ts:

export interface Store {
  container: Container | undefined;
  reactiveProperty: Ref<Property | undefined>;
  getContainer: () => Container | undefined;
  getProperty: () => Property | undefined;
}

function useStore(): Store {
  let container: Container | undefined = undefined;
  const reactiveProperty: Ref<Property | undefined> = ref();
  

  function getContainer() {
    return container;
  }

  function getProperty() {
    return property.value;
  }

  return {
    container,
    reactiveProperty,
    getContainer,
    getProperty
  };
}

const store = useStore();
export {store};

App.ts:

import {store} from '@/store';

let {container, reactiveProperty, getContainer, getProperty} = store;

onMounted(() => {
  container = new Container();
  reactiveProperty.value = new Property('foo');
  const savedContainer = getContainer(); //savedContainer is undefined
  const savedProperty = getProperty(); //savedProperty has the correct value
});

I've also tried wrapping all member accesses into getters and setters, as well as directly accessing the properties using store.container. The latter works when used in different parts of the app, but a call to getContainer() would still return undefined.

What causes this and how can I fix it?

Marcus K
  • 1
  • 1
  • 3
  • Does this answer your question? [Is JavaScript a pass-by-reference or pass-by-value language?](https://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language) – Quentin May 19 '22 at 08:48
  • @Quentin Sort of. I figured it'd be something related to passing semantics in JS, but I haven't figured out yet how exactly I need to change my code to work properly. – Marcus K May 19 '22 at 09:02

0 Answers0