在 Blazor 中使用 javascript 模块

问题描述 投票:0回答:1

我想在 Blazor 的模块中组织 javascript 代码。

我遵循了有关此主题的一些 javascript 教程,但不适用于 blazor。

这是一个简单的例子。 从 blazor 模板开始,我添加了 2 个 js 文件。

enter image description here

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>-->

现在我收到以下错误:

enter image description here

我怎样才能让它发挥作用?

javascript asp.net-core blazor
1个回答
0
投票

您必须异步导入模块,例如:

let jsModule = await JSRuntime.InvokeAsync<IJSObjectReference>("import", "/Scripts/module1.js"); 
await jsModule.InvokeAsync("Increment", currentCount);

有关更多信息,请参阅他们的文档:https://learn.microsoft.com/en-us/aspnet/core/blazor/javascript-interoperability/call-javascript-from-dotnet?view=aspnetcore-7.0#javascript- javascript 模块中的隔离

© www.soinside.com 2019 - 2024. All rights reserved.