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?

2
  • Does this answer your question? Is JavaScript a pass-by-reference or pass-by-value language? Commented May 19, 2022 at 8: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. Commented May 19, 2022 at 9:02

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.