首页 > 解决方案 > 从 HTML 中的 JavaScript 模块调用函数

问题描述

比如说,我有以下使用 Vue 的 JavaScript 模块:

import Vue from "./vue/vue.esm.browser.js";

const app = new Vue({
    el: '#app',
    data: {
        message: 'Hello, world!',
    }
});

// Custom function for calling by the button
function changeMessage() {
    app.message = 'Hello from button!';
}

现在我指的是这个模块:

<script src="js/site.js" type="module"></script>

然后我尝试打电话changeMessage

<button onclick="changeMessage();">Press me</button>

但是,我在控制台中收到以下错误:

未捕获的 ReferenceError:在 HTMLButtonElement.onclick 中未定义 changeMes​​sage

此外,在 Visual Studio 中,我什至在 IntelliSense 中都没有。当我删除type="module"时,一切正常。如何让html看到模块功能?

标签: javascriptvue.js

解决方案


您可以在全局window对象上定义函数:

<script type="module">

  window.greet = function () {
    alert('Hello')
  }

</script>

<button onclick="greet()">Hello</button>


推荐阅读