javascript - 从 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 中未定义 changeMessage
此外,在 Visual Studio 中,我什至在 IntelliSense 中都没有。当我删除type="module"
时,一切正常。如何让html看到模块功能?
解决方案
您可以在全局window
对象上定义函数:
<script type="module">
window.greet = function () {
alert('Hello')
}
</script>
<button onclick="greet()">Hello</button>
推荐阅读
- postgresql - 为什么交叉表查询返回多行而不是一行?
- javascript - 无法通过其默认构造函数动态实例化我的自定义元素
- amazon-cloudwatch - 将事件从一个 CloudWatch 日志流传输到另一个
- python - read_excel vs read_csv:object-dtype 列行为
- r - 将字符添加到列中的重复行
- xcode - 防止接口名称在 OSX 包中公开
- node.js - node js中是否有任何地址验证api?
- python - 通过操作系统限制 Environment.yml 依赖项
- nfc - NFC 读取器 ACR122U 和 libnfc.driver.acr122_usb 无法写入 USB(结果太大)
- development-environment - wix 中的库存检查器 api