我正在努力理解浏览器到底是如何处理ES6模块的。我认为,模块只会在第一次导入时执行(模块: javascript.info。
假设我有以下项目结构:
js
admin.js
customers.js
index.js
customers.html
index.htmlindex.js和customers.js都导入相同的模块admin.js。当我在index.html中导入index.js时,admin的名称从"John“更改为"Pete”,并按照预期进行了记录。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Modules</title>
</head>
<body>
<nav><a href="customers.html">Customers</a></nav>
<h1>Homepage</h1>
<script type="module" src="js/index.js"></script>
</body>
</html>在customers.html中,我希望管理员的名字也是"Pete“:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Customers</title>
</head>
<body>
<nav><a href="index.html">Home</a></nav>
<h1>Customers</h1>
<script type="module" src="js/customers.js"></script>
</body>
</html>但再次记录的不是"Pete",而是"John“。
我使用的模块:
// admin.js
export let admin = {
name: "John",
};
//index.js
import { admin } from "./admin.js";
admin.name = "Pete";
console.log(admin.name); // Pete
// customers.js
import { admin } from "./admin.js";
console.log(admin.name); // Pete1:https://javascript.info/modules-intro#a-module-code-is-evaluated-only-the-first-time-when-imported)
发布于 2020-09-23 18:54:06
正如Felix上面所说的,每个页面渲染/重新渲染都会重新加载所有资产。这就是单页应用程序和多页应用程序之间的区别。您正在使用的是一个MPA,因此您需要在页面之间提供某种形式的数据持久性,比如在数据服务器端建立数据库并在每次页面加载时请求它,或者将必要的持久性数据放在localStorage或sessionStorage中,以便在页面之间进行访问。
https://stackoverflow.com/questions/63992866
复制相似问题