gpt4 book ai didi

javascript - 我的 Javascript 应该去哪里查看组件?

转载 作者:可可西里 更新时间:2023-11-01 02:26:04 25 4
gpt4 key购买 nike

我正在习惯 view components在 MVC 6 中,我问了一个 similar question几年前关于偏颇的看法。如果我构建一个 View 组件封装一个需要自己的 Javascript 的常见用例,我应该把那个 Javascript 放在哪里?我知道它是 dangerous at best在部分 View 中使用 Javascript,但将它包含在 View 组件中会简单得多,而不是包含在包含 View 或必须由包含 View 引用的单独文件中。

例如,假设我有一个包含两个下拉菜单的 View 组件。第一个下拉列表中的选择决定了第二个下拉列表中显示的项目。当然,这在 Javascript 中很容易处理,但我应该把它放在哪里呢?

最佳答案

根据我在 ASP.NET 5 View 组件方面的经验,我认为最好的做法是将它们隔离并放在一个地方,这样它们在长期项目中就很容易管理。

在我的一个 ASP.NET 项目中,我开发了如下所示的 View 组件结构:

View Components structure

View 、后端代码和模型都在一个地方,所以当你在文件夹中移动时,你肯定会移动整个组件。此外,当您修改它们时,您可以快速访问它们的所有部分。

将与组件高度耦合的JavaScript也放在这样的结构中会很方便。您可以通过简单地在组件的文件夹下创建文件,然后编写一个 GULP TASK 将 JS 文件复制到 wwwroot 来完成此操作。从那时起,您将能够使用标准语法在组件的 .cshtml 上链接该 JavaScript 代码:

<script src="~/Components/yourcomponent.js"></script>

为了在我的项目中获得这样的结构,我扩展了 Razor,以便能够在适当的位置搜索我的组件的 CSHTML。为此,我在 Startup.cs 中添加了以下代码:

public partial class Startup
{
public void ConfigureServices(IServiceCollection services)
{
//non relevant code skipped
services.AddMvc().AddRazorOptions(ConfigureRazor);

}

public void ConfigureRazor(RazorViewEngineOptions razor)
{
razor.ViewLocationExpanders.Add(new ViewLocationExpander());
}
}

ViewLocationExpander 类是:

public class ViewLocationExpander : IViewLocationExpander
{
protected static IEnumerable<string> ExtendedLocations = new[]
{
"/{0}.cshtml"
};

public void PopulateValues(ViewLocationExpanderContext context)
{
//nothing here
}

public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations)
{
//extend current view locations
return viewLocations.Concat(ExtendedLocations);
}
}

然后,您像这样调用组件(从任何 .cshtml View ):

@await Component.InvokeAsync("NavigationComponent",new NavigationComponentModel())

关于javascript - 我的 Javascript 应该去哪里查看组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34932699/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com