打字稿 - 为什么全局导出的变量在某些情况下设置在其他情况下的某些情况下是否不确定?
我正在尝试在vue.js应用程序中拥有共享的全局变量存储。由于只有某些属性与实际应用的状态有关,因此只有这些属性包裹在VUE反应性参考对象中。但是,那些不被裁判包裹的人在不同上下文/范围内没有一致的值。这是代表我要做的示例代码:
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
});
我还尝试将所有成员访问包装到getters和setter中,并使用store.container < /代码>。后者在应用程序的不同部分中使用时起作用,但是调用
getContainer()
仍然会返回未定义。
是什么原因导致了这一点,我该如何解决?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论