【问题标题】:What alternative can I use instead of window[] for global variables对于全局变量,我可以使用什么替代方法代替 window[]
【发布时间】:2020-05-21 17:53:48
【问题描述】:

目前,我拥有的现有代码正在使用
window['heatMapStartDate'] = "@Model.HeatMapStartDate.ToString("yyyy-MM-dd")

window['heatMapEndDate'] = "@Model.HeatMapEndDate.ToString("yyyy-MM-dd")

我想删除这些,因为我无法在打字稿文件中检查它们的引用。我正在寻找一种在 .cs 文件而不是 .cshtml 文件上使用它们的方法。任何建议将不胜感激。

home.ts

const myApp = new Vue({
    el: '#dashboard',
    data: {
        heatMapStartDate: (window as any).heatMapStartDate as string,
        heatMapEndDate: (window as any).heatMapEndDate as string,
    },
    methods: {
         ...
    },
});

Index.cshtml

@page
@model JorgeApp.Pages.Dashboard.Home.IndexModel

<div id="dashboard">
    ...
</div>

<script>
    window['heatMapStartDate'] = "@Model.HeatMapStartDate.ToString("yyyy-MM-dd")";
    window['heatMapEndDate'] = "@Model.HeatMapEndDate.ToString("yyyy-MM-dd")";
</script>

Index.cshtml.cs

namespace JorgeApp.Pages.Dashboard.Home
{
    public class IndexModel : Models.PageModels.DashboardModel
    {
        ...

        public DateTime HeatMapStartDate { get; set; }
        public DateTime HeatMapEndDate { get; set; }

        ...

        public ActionResult OnGet()
        {  

            HeatMapEndDate = DateTime.UtcNow.Date.AddDays(-1);
            HeatMapStartDate = HeatMapEndDate.AddDays(-7);

            return Page();
        }
    }
}

【问题讨论】:

  • 这是什么意思:“我无法检查他们在打字稿文件上的引用。”?
  • 当我在 .ts 文件上时,我尝试查找 (window as any).heatMapStartDate as string 的所有引用,但我什么也没得到。
  • 在常用的 HTML 元素上使用 data- 属性。例如,data-heat-map-start-date="@Model.HeatMapStartDate.ToString("yyyy-MM-dd")" 然后在您的元素中执行您在 Vue.js 中执行的任何操作以访问元素的属性以获取值。

标签: javascript c# html typescript vue.js


【解决方案1】:

您可以尝试使用浏览器 localstorage 在特定域中全局存储数据,或者您可以使用浏览器 sessionstorage 通过特定会话(浏览器选项卡会话)全局存储数据。

localstorage['heatMapStartDate'] = "@Model.HeatMapStartDate.ToString("yyyy-MM-dd")";

sessionStorage['heatMapStartDate'] = "@Model.HeatMapStartDate.ToString("yyyy-MM-dd")";

您可以通过以下方式访问这些数据;

data: { heatMapStartDate: localstorage['heatMapStartDate'] as string }

data: { heatMapStartDate: sessionStorage['heatMapStartDate'] as string }

【讨论】:

    【解决方案2】:

    您可以使用 TypeScript 声明文件(例如 global.d.ts)在窗口对象上声明其他属性:

    declare global {
        interface Window { 
            heatMapStartDate: string;
            heatMapEndDate: string;
        }
    }
    

    然后你可以像这样使用它们:

    window.heatMapStartDate = "@Model.HeatMapStartDate.ToString("yyyy-MM-dd")";
    window.heatMapStartDate = "@Model.HeatMapEndDate.ToString("yyyy-MM-dd")";
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-06
      • 1970-01-01
      相关资源
      最近更新 更多