如何在多个文件之间共享全局变量?

时间:2022-06-16 16:49:38

I have two files that both need a global variable. I have a click button. When it's clicked, runs a function. The code looks like this:

我有两个文件都需要一个全局变量。我有一个点击按钮。单击它时,运行一个函数。代码如下所示:

file1:

文件1:

var globalVar = '', // The global variable

<button onClick = {() => this.edit(arg1)}></button>
function edit (arg1){

   globalVar = arg1;
}

module.exports = globalVar;

I have another file, looks like this:

我有另一个文件,看起来像这样:

file2:

文件2:

var globalVar = require(./file1);

function openModal(){

if (globarVar != ''){
 do something

} }

}}

The issue is that when I click button, the globalVar is updated in the edit() function, but I console.log(globalVar) in file2 it shows ' '.My question is how do I pass the globalVar to file2 when I click the button?

问题是,当我单击按钮时,globalVar在edit()函数中更新,但我在file2中的console.log(globalVar)显示''。我的问题是当我单击时如何将globalVar传递给file2按钮?

1 个解决方案

#1


0  

If you truly want a global variable (not advisable, of course) then you're always 100% free to do

如果你真的想要一个全局变量(当然不可取),那么你总是可以100%*地做

window.globalVar = 0;

window.globalVar = 0;

in any of your modules.

在任何模块中。


The more robust solution would of course be to have this global variable sit in some sort of dedicated module, like

更强大的解决方案当然是将这个全局变量放在某种专用模块中,比如

globalVar.js

globalVar.js

export default {
    value: 0
};

and then you could

然后你可以

import globalVal from './globalVar';

globalVal.value = 'whatever';

from any modules needed.

从任何需要的模块。

The only risk would be that webpack might duplicate this same "global" value into multiple bundles if you're code splitting, depending on your setup. So separate module would be using their own local copy of this not-so-global variable.

唯一的风险是,如果您进行代码拆分,webpack可能会将此相同的“全局”值复制到多个捆绑包中,具体取决于您的设置。因此,单独的模块将使用它们自己的这个不那么全局变量的本地副本。

#1


0  

If you truly want a global variable (not advisable, of course) then you're always 100% free to do

如果你真的想要一个全局变量(当然不可取),那么你总是可以100%*地做

window.globalVar = 0;

window.globalVar = 0;

in any of your modules.

在任何模块中。


The more robust solution would of course be to have this global variable sit in some sort of dedicated module, like

更强大的解决方案当然是将这个全局变量放在某种专用模块中,比如

globalVar.js

globalVar.js

export default {
    value: 0
};

and then you could

然后你可以

import globalVal from './globalVar';

globalVal.value = 'whatever';

from any modules needed.

从任何需要的模块。

The only risk would be that webpack might duplicate this same "global" value into multiple bundles if you're code splitting, depending on your setup. So separate module would be using their own local copy of this not-so-global variable.

唯一的风险是,如果您进行代码拆分,webpack可能会将此相同的“全局”值复制到多个捆绑包中,具体取决于您的设置。因此,单独的模块将使用它们自己的这个不那么全局变量的本地副本。