【问题标题】:Displaying reusable VueJS chart component in Blazor在 Blazor 中显示可重用的 VueJS 图表组件
【发布时间】:2020-08-30 16:18:37
【问题描述】:

我想像 this 教程中的可重用组件一样使用 this 图表。

图表组件应该接受一些输入参数并显示由 VueJS 渲染的图表。 Blazor 不允许在 *.razor 文件中添加 script 标签,所以我改用 *.cshtml

/Pages/Index.razor - 主页

@page "/"

<ChartComponent></ChartComponent>

/Shared/ChartComponent.cshtml - 显示在页面上的组件

<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

问题

如果我将 JS 放入 Host.cshtml 中,一切正常,但是当我尝试将其设为单独的 CSHTML 组件时,主页会抱怨 ChartComponent 未定义。 CSHTML 可以是一个组件还是我需要将它作为老式 MVC 部分包含在内?

【问题讨论】:

    标签: blazor asp.net-blazor


    【解决方案1】:

    您的组件中不能有脚本,它们应该从您的 _Host.cshtml(或 index.html,如果您使用 Blazor WASM)中的单独文件加载。并在应用程序启动之前加载。

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

    【讨论】:

    • VueJS 脚本使用新的 HTML 标签 &lt;chart-control&gt; 创建一个 Web 组件。我在Index 页面上使用这个标签。如果我把所有脚本都放到Host.cshtml,主机在Index页面之前加载JS,JS找不到并初始化&lt;chart-control&gt;,所以Web组件没有被渲染。有没有办法在不拆分 Host.cshtml 和 Index.razor 的情况下将 HTML 和 JS 保持在一起?
    • 基本上,我需要确保每次进入特定页面时都执行 JS 脚本。
    • 使用 JSInterop 在组件 OnIntializedAsync 上启动脚本
    • 或者在 AfterRenderAsync 上,我不确定它是否可以在 OnInitializedAsync 上工作
    猜你喜欢
    • 2021-06-01
    • 2020-06-29
    • 2021-11-13
    • 1970-01-01
    • 2019-02-10
    • 1970-01-01
    • 1970-01-01
    • 2020-01-09
    • 2023-04-04
    相关资源
    最近更新 更多