我想在 Blazor 的模块中组织 javascript 代码。
我遵循了有关此主题的一些 javascript 教程,但不适用于 blazor。
这是一个简单的例子。 从 blazor 模板开始,我添加了 2 个 js 文件。
main.js 包含:
function Increment(value) {
value++;
DisplayVal(value);
return value;}
module1.js 包含:
function DisplayVal(value) {
console.log("The value is " + value);}
在柜台页面我添加了 @注入IJSRuntime JS 和
private async Task IncrementCount()
{
//currentCount++;
currentCount = await JS.InvokeAsync<int>("Increment", currentCount);
}
在index.html中我添加了
<script src="/Scripts/main.js" autostart="false"></script>
<script src="/Scripts/module1.js" autostart="false"></script>
到目前为止一切正常。
现在我想将 module1.js 转换为模块。 我添加导出标签
export function DisplayVal(value) {
console.log("The value is " + value);
}
主要。我添加了js
import { DisplayVal } from "./module1.js"
在index.html中我更改如下:
<script type="module" src="/Scripts/main.js" autostart="false"></script>
<!--<script src="/Scripts/module1.js" autostart="false"></script>-->
现在我收到以下错误:
我怎样才能让它发挥作用?
您必须异步导入模块,例如:
let jsModule = await JSRuntime.InvokeAsync<IJSObjectReference>("import", "/Scripts/module1.js");
await jsModule.InvokeAsync("Increment", currentCount);