繁体   English   中英

不能在代码中使用js文件中导入的var

[英]can't use imported var from js file in code

我尝试将js文件中导入的变量用于我的代码,但我不能让它以除外的方式工作。

location_var.js

var location = {

    place: "Bogotá",
    lat: "4.710988599999999",
    lng: "-74.072092"

};
export { location };

的index.html

<script type="module">
    import { location } from './location_var.js'
    console.log(location.lat) // this will be displayed
</script>

但如果我在下面放一个<script>标签,我就不能再使用我的变量了。

<body>
    <!--The div element for the map -->
    <div id="map"></div>
    <script>
        function initMap() {
            var place = { lat: location.lat, lng: location.lng }; // this doesn't work - console says the vars are undefined for some reasons
            var map = new google.maps.Map(
                document.getElementById('map'), { zoom: 4, center: place });
            var marker = new google.maps.Marker({ position: place, map: map });
        }
    </script>
    <script async defer
        src="https://maps.googleapis.com/maps/api/js?key=API_KEY&callback=initMap">
        </script>
</body>

任何想法为什么我不能在那里回电话?

模块中定义(或导入)的变量在该模块中具有范围。 如果<script type="module">定义或导入某些内容,则在任何其他<script>标记中都不会显示它。

与普通脚本不同,使用const / let / var和函数声明定义的变量名称不会被放入全局环境中,因此即使您将导入的location放入独立变量,也无济于事。

另一个问题是你在这里有两个异步操作:你必须得到location_var.js来获取location对象,你还必须等待下载googleapis脚本。 无论是脚本依赖于其他,但要运行的东西(初始化地图) 已经完成了。 要等待多个异步事件完成然后运行其他东西,你应该使用Promise.all ,并且要使用Promise.all ,你需要确保每个异步操作在完成后解析Promise。 所以,这是一种可能的方法:

<script>
window.googleScriptPromise = new Promise((resolve) => {
  window.googleScriptCallback = resolve;
});
window.locationPromise = new Promise((resolve) => {
  window.locationResolve = resolve;
});

Promise.all([
  locationPromise
  googleScriptPromise,
])
  .then(([location]) => {
    // now, location will refer to the imported location, and google maps will have been loaded
  });
</script>

<script async defer
    src="https://maps.googleapis.com/maps/api/js?key=API_KEY&callback=googleScriptCallback">
    </script>
<script type="module">
  import { location } from './location_var.js'
  window.locationPromise(location);
</script>

这会保留您当前的<script>结构,但它依赖于一堆全局变量。 如果您没有为大部分代码单独使用<script>标记,而是将大部分代码放在模块中,那么您可能会更好一些,这样您只需要在Google承诺上调用.then

<script>
// must use a normal script tag to assign the Promise to window synchronously
window.googleScriptPromise = new Promise((resolve) => {
  window.googleScriptCallback = resolve;
});
</script>
<script async defer
    src="https://maps.googleapis.com/maps/api/js?key=API_KEY&callback=googleScriptCallback">
    </script>
<script type="module">
import { location } from './location_var.js'
window.googleScriptPromise.then(() => {
  // now, location will refer to the imported location, and google maps will have been loaded
});
</script>

如果您能够更改<script>的大部分内容,则上述方法更清晰,绝对更可取。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM