[英]Problem with JavaScript files in Blazor component
我在 Blazor 組件(Blazor 服務器和 .net 6)中使用 JavaScript 文件。 如下:
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
await jsRuntime.InvokeAsync<IJSObjectReference>("import", "/css/template/vendor/libs/bs-stepper/bs-stepper.js");
}
}
第一次加載頁面時一切正常,但是當我使用導航更改頁面並進入另一個頁面(組件)然后再次返回與上一頁相同時,無法使用 JavaScript 代碼。
這個問題的原因是什么?
這是在 blazor 應用程序中使用 javascript 庫的方法。
在index.html
(或_Layout.cshtml
)的body
元素末尾添加庫的腳本
<body>
...
<script src="css/template/vendor/libs/bs-stepper/bs-stepper.js"></script>
...
</body>
和head
元素末端的 css
<head>
...
<link rel="stylesheet" href="css/template/vendor/libs/bs-stepper/bs-stepper.min.css">
...
</head>
在路徑wwwroot/js
中創建一個名為stepperInteropHelper.js
的 js 文件,並在其中添加此 function:
export function initStepper() {
new Stepper(document.querySelector('.bs-stepper'));
}
最后在使用步進器的組件中:
@inject IJSRuntime jsRuntime
<div class="bs-stepper">
...
</div>
@code {
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
// import stepperInteropHelper.js module
IJSObjectReference module = await jsRuntime.InvokeAsync<IJSObjectReference>(
"import", "./js/stepperInteropHelper.js");
// call initStepper method from stepperInteropHelper.js
await module.InvokeVoidAsync("initStepper");
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.