How to automatically execute a js event (non-click event) when dotNetCore Blazor loads an index.razor page

半世苍凉 提交于 2020-01-24 20:38:09

问题


Excuse me, everyone, how to enter Index.razor to automatically execute a js event

The carousel plugin used needs to automatically execute the following code

function(){
    $("#banner").owlCarousel({
        autoPlay : 3000,
        paginationSpeed : 1000,
        goToFirstSpeed : 2000,
        singleItem : true,
        autoHeight : true,
        navigation: true,
        transitionStyle: 'fade'
    });
}

Such ineffective no longer should need to load the event in the child page _Host.cshtml

出现一个错误 Index.razor

出现Object reference not set to an instance of an object.


回答1:


Just create a JS interop function like that :

wwwroot/scripts/interop.js

window.carousel = {
   play: (id, options) => {
     $(id).owlCarousel(options);
   } 
}:

Launch it when your carousel at id is ready in your razor page or component.

Index.razor

@inject IJSRuntime _jsRuntime

<div id="banner"></div>

@code {
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
       if (!firstRender)
       {
           return;
       }
       await _jsRuntime.InvokeVoidAsync("carousel.play", "#banner", new
       {
            autoPlay = 3000,
            paginationSpeed = 1000,
            goToFirstSpeed = 2000,
            singleItem = true,
            autoHeight = true,
            navigation = true,
            transitionStyle = "fade"
       });
    }
}

And launch your script in the _Host.cshtml

    <script src="scripts/interop.js"></script>


来源:https://stackoverflow.com/questions/59134029/how-to-automatically-execute-a-js-event-non-click-event-when-dotnetcore-blazor

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!