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?