Get current Url in a Blazor component

前端 未结 3 1269
渐次进展
渐次进展 2020-11-30 03:35

I need to know the url of the current page in order to check if I have to apply certain style to a element. The code below is an example.

@using Microsoft.As         


        
3条回答
  •  -上瘾入骨i
    2020-11-30 04:30

    You should listen to a LocationChange of the IUriHelper, which triggers the function to do what you want for example:

    @using Microsoft.AspNetCore.Blazor.Components
    @using Microsoft.Extensions.Logging
    @inject Microsoft.AspNetCore.Blazor.Services.IUriHelper UriHelper
    @inject ILogger logger
    
    
    
    @functions {
        protected override void OnInit()
        {
            UriHelper.OnLocationChanged += OnLocationChanges;
        }
        [Parameter]
        private string Url { get; set; }
        [Parameter]
        private string Icon { get; set; }
        [Parameter]
        private string Text { get; set; }
        private bool Active = false;
        private void OnLocationChanges(object sender, string newLocation)
        {
            bool active = newLocation.Contains(Url);
            if(active != Active) //Only re-render the components that need it
            {
                Active = active;
                StateHasChanged();
                logger.LogInformation("Location Change To:" + newLocation);
            }
        }
    }
    

提交回复
热议问题