简体   繁体   中英

Problem with JavaScript files in Blazor component

I use JavaScript file in Blazor component (Blazor server and .net 6). as below:

protected override async Task OnAfterRenderAsync(bool firstRender)
{
    if (firstRender)
    {
        await jsRuntime.InvokeAsync<IJSObjectReference>("import", "/css/template/vendor/libs/bs-stepper/bs-stepper.js");
    }
}

When for the first time loading page everything is OK, but when I change page with nav and enter to another page (component) and after that again return to same as previous page, not working JavaScript codes.

What is the reason for this problem?

Here is how you can use javascript libraries in blazor apps.

Add the script of the library at the end of body element in your index.html (or _Layout.cshtml )

<body>
    ...
    <script src="css/template/vendor/libs/bs-stepper/bs-stepper.js"></script>
    ...
</body>

and the css at the end of head element

<head>
    ...
    <link rel="stylesheet" href="css/template/vendor/libs/bs-stepper/bs-stepper.min.css">
    ...
</head>

Create a js file named eg stepperInteropHelper.js in path wwwroot/js and inside add this function:

export function initStepper() {
    new Stepper(document.querySelector('.bs-stepper'));
}

Finally in your components that use a 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");
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM