Search code examples
blazorasp.net-blazor

Displaying reusable VueJS chart component in Blazor


I want to use this chart like a reusable component from this tutorial.

The chart component should accept some input parameters and display chart rendered by VueJS. Blazor doesn't allow to add script tags inside *.razor files, so I'm using *.cshtml instead.

/Pages/Index.razor - main page

@page "/"

<ChartComponent></ChartComponent>

/Shared/ChartComponent.cshtml - component to display on the page

<div id="charts" style="width: 300px; height: 300px; border: 1px solid red;">
  <chart-control :data="bars"></chart-control>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.min.js"></script>
<script src="~/scripts/vue-charts/library/trading-vue.js"></script>
<script>

  window.bars = {
    ohlcv: [
      [1551128400000, 33, 37.1, 14, 14, 196],
      [1551132000000, 13.7, 30, 6.6, 30, 206],
      [1551135600000, 29.9, 33, 21.3, 21.8, 74],
      [1551139200000, 21.7, 25.9, 18, 24, 140],
      [1551142800000, 24.1, 24.1, 24, 24.1, 29],
    ]
  };

  window.onload = function () {
    var vm = new Vue({
      el: '#charts',
      components: { 'chart-control': window.TradingVueLib.TradingVue }
    });
  };
</script>

/_Import.razor

@using System.Net.Http
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components
@using Microsoft.AspNetCore.Components.Authorization
@using Microsoft.AspNetCore.Components.Forms
@using Microsoft.AspNetCore.Components.Routing
@using Microsoft.AspNetCore.Components.Web
@using Microsoft.JSInterop
@using Charts
@using Charts.Shared

The problem

If I put JS into Host.cshtml, everything works fine, but when I try to make it a separate CSHTML component, main page complains that ChartComponent is not defined. Can CSHTML be a component or do I need to include it as old-school MVC partial?


Solution

  • You cannot have scripts in your components, they should be loaded from a separated file on in your _Host.cshtml (or index.html if you use Blazor WASM). And loaded before the application start.

    Call JavaScript functions from .NET methods in ASP.NET Core Blazor