简体   繁体   English

如何设置 ASP.NET 内核 + Vue.js?

[英]How do I set up ASP.NET Core + Vue.js?

I need to integrate Vue.js with some ASP.NET Core MVC views.我需要将 Vue.js 与一些 ASP.NET 核心 MVC 视图集成。 I picked Vue.js over other alternatives because it seemed to be simpler – " just add it via a <script> tag ", they said.我选择了 Vue.js 而不是其他替代品,因为它似乎更简单——“只需通过<script>标签添加它”,他们说。 No need to learn Gulp/Grunt/Webpack/Browserify/etc.无需学习 Gulp/Grunt/Webpack/Browserify/等。

That turned out to be false.事实证明这是错误的。 At my first attempt to handle dates I tried some extensions like vue-moment and vue-datetime-picker , taken from this official curated list of awesome things related to Vue.js but I hit a wall here.在我第一次尝试处理日期时,我尝试了一些扩展,例如vue-momentvue-datetime-picker picker ,这些扩展取自与 Vue.js 相关的官方精选列表,但我在这里碰壁了。 While the first does not mandate using the require() JS syntax (CommonJS?), the second one doesn't work without it.虽然第一个不要求使用require() JS 语法(CommonJS?),但第二个没有它就无法工作。 Other extensions happen to 'use babel' and imports / exports which is ECMAScript 6 that needs to be compiled.其他扩展碰巧'use babel'imports / exports ,这是需要编译的 ECMAScript 6。 So, most Vue.js libraries and toolings indeed need a compiler, plus the require() syntax, and all that stuff from the Node world?所以,大多数 Vue.js 库和工具确实需要编译器,加上require()语法,以及来自 Node 世界的所有东西?

How should I set up my project to work with ASP.NET Core MVC + Vue.js, in a way that I can develop many small Vue apps using Vue plugins (that can require(stuff) )?我应该如何设置我的项目以使用 ASP.NET Core MVC + Vue.js,以便我可以使用 Vue 插件(可能require(stuff) )开发许多小型 Vue 应用程序?

I was totally lost when I asked the above question.当我问出上述问题时,我完全迷失了。 I've spent a few days and I still don't have a complete picture.我花了几天时间,我仍然没有完整的图片。 What I am pretty sure is that 2016 is a hard year to learn JavaScript .我很确定2016 年是学习 JavaScript 的艰难一年

I wanted to use Vue.js because it's simpler than the alternatives.我想使用 Vue.js,因为它比其他选择更简单。 Less ceremony, fewer boilerplates, less code.更少的仪式,更少的样板,更少的代码。 It's branded as the Progressive Framework ... Right!它被称为渐进式框架......对! But only to a point.但只是到了一定程度。 Vue.js does not solve the JavaScript ecosystem fragmentation problem with build systems. Vue.js 并没有解决构建系统的 JavaScript 生态系统碎片化问题。

So, you will have to pick a side: Do you need JavaScript modules and a build system?所以,你将不得不选择一个方面:你需要 JavaScript 模块和构建系统吗?

Option 1: Keep it simple: Avoid JS modules and build systems.选项 1:保持简单:避免使用 JS 模块和构建系统。

Reasons to follow this path:走这条路的原因:

  • You don't have many days to learn A LOT of stuff.你没有多少天可以学习很多东西。 (Configuring bundler, npm+package dependencies hell, ES6 stuff.) (配置捆绑器,npm+package 依赖地狱,ES6 的东西。)
  • You do not want to make a bleeding-edge single-page application.您不想制作最前沿的单页应用程序。 Embedding Vue.js inside a few HTML pages seems enough.在几个 HTML 页面中嵌入 Vue.js 似乎就足够了。
  • HTTP/2 is becoming mainstream, so bundlers like Webpack or Browserify will provide fewer benefits, at least on performance. HTTP/2 正在成为主流,因此像 Webpack 或 Browserify 这样的打包工具将提供更少的好处,至少在性能方面是这样。
  • Eventually ES6 modules will be supported directly in the browser, so we won't need to build whatever the latest JavaScript is into browser-compatible JavaScript. 最终,浏览器将直接支持 ES6 模块,因此我们不需要将最新的 JavaScript 构建到与浏览器兼容的JavaScript 中。

You will save many days by not spending time learning stuff that will probably be obsolete in a few years.不用花时间学习几年后可能会过时的东西,你会节省很多天。

If you follow this path, a few recommendations:如果您遵循此路径,有一些建议:

  • Just add JS libraries using the <script> tag.只需使用<script>标签添加 JS 库。
  • Only use browser-ready JavaScript libraries.仅使用浏览器就绪的 JavaScript 库。 Code that uses require() or the UMD prefix (function (root, factory) { requires you set up modules (therefore it is not browser-ready unless you set up CommonJS). JS files with import / export statements are written in ES6 so avoid them too.使用require()或 UMD 前缀(function (root, factory) {的代码需要您设置模块(因此,除非您设置 CommonJS,否则它不是浏览器就绪的)。带有import / export语句的 JS 文件是用 ES6 编写的,所以也避免它们。
  • Use Bower to download browser-ready libs.使用 Bower 下载浏览器就绪的库。 Avoid NPM (which implies having a module system in place).避免使用 NPM(这意味着有一个模块系统)。

Caveat: You will not be able to use advanced Vue.js features like single-file components or Vue Router, but that is OK.警告:您将无法使用高级 Vue.js 功能,如单文件组件或 Vue 路由器,但没关系。 You will have to do a few things manually.您将不得不手动执行一些操作。

Option 2: Learn JavaScript modules + build systems.选项 2:学习 JavaScript 模块 + 构建系统。

Prepare a few days to learn and not code.准备几天学习而不是编码。 I will only explain briefly how Webpack worked for me.我只会简要解释 Webpack 如何为我工作。 Browserify also works, but I haven't tried it. Browserify 也可以,但我没试过。

I recommend you spend some time learning what JavaScript modules are .我建议您花一些时间了解什么是JavaScript 模块 Then learn to build them and pack them: I used Webpack.然后学习构建它们并打包它们:我使用了 Webpack。 Its documentation is not great, so what worked for me was to follow its tutorial step by step.它的文档不是很好,所以对我有用的是一步一步地遵循它的教程

At this point, you may have heard that Webpack ALSO has a built-in web server with "hot module reloading".此时,您可能已经听说 Webpack ALSO 有一个内置的 Web 服务器,具有“热模块重载”功能。 This is a web server for static files to be used only for development.这是仅用于开发的静态文件的 Web 服务器。 Its benefit is that whenever you edit a JS module, the browser will automatically apply the change without refreshing.它的好处是每当你编辑一个 JS 模块时,浏览器会自动应用更改而无需刷新。 This is a very nice, but optional, feature.这是一个非常好的但可选的功能。 The problem: this built-in web-server competes with our web server (Kestrel).问题:这个内置的网络服务器与我们的网络服务器(Kestrel)竞争。 So, if you want to try this feature during development use the Webpack ASP.NET Core middleware provided at Microsoft's JavaScriptServices repo .因此,如果您想在开发过程中尝试此功能,请使用 Microsoft 的JavaScriptServices存储库中提供的Webpack ASP.NET Core 中间件 There you will find the WebApplicationBasic template that I am currently using.在那里你会找到我当前使用的WebApplicationBasic 模板 I dissected it, removed most of its parts and by trying to use it I slowly understood what each part was originally for.我解剖了它,去掉了它的大部分部分,通过尝试使用它,我慢慢地理解了每个部分最初的用途。

When using Webpack you will mostly use 3 workflows:使用 Webpack 时,您将主要使用 3 个工作流程:

  • Built-in development mode: Creates huge files, easy for debugging.内置开发模式:创建大文件,便于调试。 Use it together with 'watch-mode' so whenever you modify a file, a new Webpack build is triggered.将它与 'watch-mode' 一起使用,因此每当您修改文件时,都会触发新的 Webpack 构建。
  • Built-in production mode: Creates small minified files.内置生产模式:创建小型缩小文件。 Useful for 'dotnet publish'.对于“dotnet 发布”很有用。
  • Using Webpack's web server and hot module reloading with the Webpack ASP.NET Core middleware means your app will run Webpack in the background, build, and watch the source files for changes.使用 Webpack 的 Web 服务器和热模块重新加载与 Webpack ASP.NET Core 中间件意味着您的应用程序将在后台运行 Webpack、构建并观察源文件的更改。 The compilation output is not written to disk and only kept in memory and served via HTTP.编译输出不写入磁盘,只保存在内存中并通过 HTTP 提供。 The JavaScriptServices middleware forwards requests from Kestrel to Webpack's web server to make this work. JavaScriptServices 中间件将来自 Kestrel 的请求转发到 Webpack 的 Web 服务器以完成这项工作。

Whatever Webpack config you go with, you have to include 'vue-loader' in your Webpack config.无论你使用什么 Webpack 配置,你都必须在你的 Webpack 配置中包含“vue-loader”。 You may be inspired by Vue's webpack-simple template .你可能会受到Vue 的 webpack-simple 模板的启发。

I haven't covered everything that I wanted to, but this topic is too extensive and I need to go back to coding.我没有涵盖我想要的所有内容,但是这个主题太广泛了,我需要回到编码。 Please leave some feedback.请留下一些反馈。

I'm late to the party but there is now a template available for .NET Core that you can build with a single command.我迟到了,但现在有一个可用于 .NET Core 的模板,您可以使用单个命令构建它。 On a Windows box with .NET Core installed just create an empty folder and in that folder run this command to show a list of available templates:在安装了 .NET Core 的 Windows 机器上,只需创建一个空文件夹,然后在该文件夹中运行此命令以显示可用模板的列表:

dotnet new

If you don't have all the templates, you just need to run this to install the SPA templates:如果你没有所有的模板,你只需要运行这个来安装 SPA 模板:

dotnet new --install Microsoft.AspNetCore.SpaTemplates::*

And this to scaffold a new Vue app:这将搭建一个新的 Vue 应用程序:

dotnet new vue

In milliseconds a complete new Vue.js single-page web app is built with a working .NET Core back end with controllers, views etc. It's brilliant.只需几毫秒,一个全新的 Vue.js 单页 Web 应用程序就可以使用带有控制器、视图等的有效 .NET Core 后端构建。这非常棒。 Just open the project in VS or VS Code and you're away.只需在 VS 或 VS Code 中打开项目即可。

There are also templates for Aurelia, Angular, Knockout and React!还有 Aurelia、Angular、Knockout 和 React 的模板! You can build them all and compare how each solves the same problem.您可以构建它们并比较它们如何解决相同的问题。 The Angular one even does server side pre-rendering out of the box! Angular 甚至可以开箱即用地进行服务器端预渲染!

I know .NET Core has a way to go but it's becoming more and more awesome by the day!我知道 .NET Core 有一段路要走,但它变得越来越棒!

First, a disclaimer: I couldn't find anything that really fit what I needed, so I put together a solution from scratch.首先,免责声明:我找不到真正适合我需要的东西,所以我从头开始整理了一个解决方案。 See the end.见结尾。

You ask about including Vue via the <script> tag (in that case the CDN build).您询问是否通过<script>标签包含 Vue(在这种情况下是 CDN 构建)。 However, you also mention using Babel and the ES6 modules feature.但是,您还提到了使用 Babel 和 ES6 模块功能。 In that case I would recommend using Webpack for the client-side app, which will compile your ES6 with Babel, allow you to use modules and components, and work with a template!在这种情况下,我建议将 Webpack 用于客户端应用程序,它将使用 Babel 编译您的 ES6,允许您使用模块和组件,并使用模板! You also get hot module reloading (edit your source and see changes in the client app in real time!) and Webpack will bundle your SPA into a static HTML5 app.您还可以重新加载热模块(编辑源代码并实时查看客户端应用程序中的更改!)并且 Webpack 会将您的 SPA 捆绑到静态 HTML5 应用程序中。

The official Vue.js docs point to their own Webpack template . Vue.js 官方文档指向他们自己的 Webpack 模板

So you can run the Webpack dev server and your ASP.NET Core app independently, if that suits your needs, but there's a better solution that makes development even more streamlined:因此,您可以独立运行 Webpack 开发服务器和 ASP.NET Core 应用程序,如果这适合您的需求,但有一个更好的解决方案可以使开发更加简化:

Microsoft's open-source JavaScriptServices lets you execute Node.js from ASP.NET Core, and they have some Webpack middleware that integrates the Webpack dev server into your app during debug builds. Microsoft 的开源JavaScriptServices允许您从 ASP.NET Core 执行 Node.js,并且他们有一些 Webpack 中间件,可以在调试构建期间将 Webpack 开发服务器集成到您的应用程序中。

They provide official templates for Angular 2, and even a template labeled Vue.js, but the Vue template is just the official Webpack template without any integration with .NET;他们提供了 Angular 2 的官方模板,甚至还有标有 Vue.js 的模板,但 Vue 模板只是官方的 Webpack 模板,没有与 .NET 进行任何集成; this is just like the standalone server.这就像独立服务器一样。

I couldn't find any templates that did this for Vue.js, so I put together a sample ASP.NET Core application that loads the Webpack dev middleware with a Vue.js Webpack app.我找不到任何为 Vue.js 执行此操作的模板,因此我将一个示例 ASP.NET Core 应用程序放在一起,该应用程序将 Webpack 开发中间件与 Vue.js Webpack 应用程序一起加载。 When the .NET Core server is running in dev mode, you can edit the Vue source, and the changes will be reflected with quick incremental patches without needing to rebuild the entire application.当 .NET Core 服务器在开发模式下运行时,您可以编辑 Vue 源代码,更改将通过快速增量补丁反映出来,而无需重新构建整个应用程序。 In release mode, .NET Core will use the prebuilt Webpack output.在发布模式下,.NET Core 将使用预构建的 Webpack 输出。 You can find it on GitHub:你可以在 GitHub 上找到它:

https://github.com/0xFireball/YetAnotherShrinker https://github.com/0xFireball/YetAnotherShrinker

The repository linked above has a full application demo that uses NancyFx, axios, Vue.js, and Vue Material, and is a simple URL shortener.上面链接的存储库有一个使用 NancyFx、axios、Vue.js 和 Vue Material 的完整应用程序演示,并且是一个简单的 URL 缩短器。 If you want steps for a more minimal setup that can easily be added to an existing app, check out this blog post of mine .如果您想要一个可以轻松添加到现有应用程序的更简单设置的步骤,请查看我的这篇博文

Obligatory disclosure: I wrote that blog post.强制性披露:我写了那篇博文。

Maybe someone will find this information helpful.也许有人会发现这些信息很有帮助。

Here are some starter templates you can use for a quick project setup.以下是一些可用于快速项目设置的入门模板。

The first one gives you a multi-project solution with some predefined architecture.第一个为您提供了具有一些预定义架构的多项目解决方案。 This template more closely matches real-world projects than the JavaScriptServices solution which was already mentioned here.这个模板比这里已经提到的 JavaScriptServices 解决方案更接近现实世界的项目。 It provides a domain layer, repository layer, etc. Note that this is a Yeoman generator and it uses TypeScript.它提供了域层、存储库层等。请注意,这是一个 Yeoman 生成器,它使用 TypeScript。 https://github.com/vue-typed/generator-vue-net-core https://github.com/vue-typed/generator-vue-net-core

The second is just a project on GitHub and you should clone it if you want to use it.第二个只是 GitHub 上的一个项目,如果你想使用它,你应该克隆它。 It is not a Yeoman generator and I think this is regrettable, but I found the structure in this template better than in the first one.它不是 Yeoman 生成器,我认为这很遗憾,但我发现这个模板中的结构比第一个更好。 Also, it has a lot of nice little things like some exception filters, that you, most likely, will still do anyway.此外,它还有很多不错的小东西,比如一些异常过滤器,你很可能仍然会这样做。 And if you are a beginner, this template will be just a godsend.如果你是初学者,这个模板简直是天赐之物。 This template is recommended on the awesome-vue page.推荐在 awesome-vue 页面上使用此模板。 Here's the link: https://github.com/mrellipse/toucan这是链接: https ://github.com/mrellipse/toucan

You can try the steps below, from this simple guide .您可以从这个简单的指南中尝试以下步骤。

  1. Set up the npm configuration file (package.json)设置 npm 配置文件(package.json)

Below is the npm package I will use:下面是我将使用的 npm 包:

 { "version": "1.0.0", "name": "asp.net", "private": true, "scripts": { "prod": "gulp --production", "dev": "gulp watch" }, "devDependencies": { "gulp": "^3.9.1", "laravel-elixir": "^6.0.0-14", "laravel-elixir-vue-2": "^0.2.0", "laravel-elixir-webpack-official": "^1.0.2", "vue": "^2.0.1", "vue-resource": "^1.0.3", "vuex": "^2.1.1" } }
  1. Install the npm package安装 npm 包

Open a command prompt and go to the root folder of your application and install the npm packages set from your package.json file using the command 'npm install', without the quotes.打开命令提示符并转到应用程序的根文件夹并使用命令“npm install”安装从 package.json 文件设置的 npm 包,不带引号。

  1. Set up Gulp设置 Gulp

Once the npm package is installed you may now set up the Gulp file.安装 npm 包后,您现在可以设置 Gulp 文件。 You will need to add a Gulp configuration file (gulpfile.js).您将需要添加一个 Gulp 配置文件 (gulpfile.js)。 Later on we will create the Vue JS which we will call vueApp.js with the code below.稍后我们将使用下面的代码创建 Vue JS,我们将其称为 vueApp.js。 The first argument is the public output directory and the other one is the source directory.第一个参数是公共输出目录,另一个是源目录。 For more details on Webpack click here .有关 Webpack 的更多详细信息,请单击 此处

 var elixir = require('laravel-elixir'); require('laravel-elixir-vue-2'); elixir(function (mix) { mix.webpack('vueApp.js', 'wwwroot/js/dist', 'wwwroot/js'); });
  1. Create the Vue JS file创建 Vue JS 文件

In your ASP.NET Core web app project solution explorer go to wwwroot and add a 'js' folder and if it does not exist then add again a new folder named 'dist'.在您的 ASP.NET Core Web 应用项目解决方案资源管理器中,转到 wwwroot 并添加一个“js”文件夹,如果它不存在,则再次添加一个名为“dist”的新文件夹。 Now once the folder setup is complete add a new JavaScript file in the 'js' folder named 'vueApp.js'.现在,一旦文件夹设置完成,在名为“vueApp.js”的“js”文件夹中添加一个新的 JavaScript 文件。

  1. Start coding in your Vue JS file在你的 Vue JS 文件中开始编码

You may now start coding.您现在可以开始编码了。 In the example below we will be displaying an alert to indicate that Vue.js is running.在下面的示例中,我们将显示一个警报以指示 Vue.js 正在运行。

 import Vue from 'vue' new Vue( { el: '#app', data() { message:'hello world using Vue.js on ASP.NET Core MVC.' }, mounted() { console.log(this.message); } });
  1. Apply Vue JS to your Razor view or HTML将 Vue JS 应用到 Razor 视图或 HTML

Open your layout page and wrap the content of your body tag with a div and an id of 'app'.打开你的布局页面并用一个 div 和一个 'app' 的 id 包装你的 body 标签的内容。 We will use 'app' since that is the id tag we used in our sample code from step 5. The name 'app' is not required and you may change it to your desired name.我们将使用“app”,因为这是我们在第 5 步的示例代码中使用的 id 标签。名称“app”不是必需的,您可以将其更改为您想要的名称。 Lastly add a reference to the Vue JS file.最后添加对 Vue JS 文件的引用。 Be sure to move outside the 'app' div the script references to prevent error.一定要移到脚本引用的 'app' div 之外,以防止出错。

<body>

<div id="app">

    <nav class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a asp-area="" asp-controller="Home" asp-action="Index" class="navbar-brand">Project.Payrole</a>
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li><a asp-area="" asp-controller="Home" asp-action="Index">Home</a></li>
                    <li><a asp-area="" asp-controller="Home" asp-action="About">About</a></li>
                    <li><a asp-area="" asp-controller="Home" asp-action="Contact">Contact</a></li>
                </ul>
                @await Html.PartialAsync("_LoginPartial")
            </div>
        </div>
    </nav>
    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; 2017 - Project.Payrole</p>
        </footer>
    </div>

</div>

<environment names="Development">
    <script src="~/lib/jquery/dist/jquery.js"></script>
    <script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
    <script src="~/js/site.js" asp-append-version="true"></script>
</environment>

<environment names="Staging,Production">
    <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-2.2.0.min.js"
            asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
            asp-fallback-test="window.jQuery"
            crossorigin="anonymous"
            integrity="sha384-K+ctZQ+LL8q6tP7I94W+qzQsfRV2a+AfHIi9k8z8l9ggpc8X+Ytst4yBo/hH+8Fk">
    </script>
    <script src="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/bootstrap.min.js"
            asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.min.js"
            asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal"
            crossorigin="anonymous"
            integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa">
    </script>
    <script src="~/js/site.min.js" asp-append-version="true"></script>
</environment>

<script src="~/js/dist/vueApp.js" asp-append-version="true"></script>



    @RenderSection("Scripts", required: false)
</body>
  1. Run Gulp运行 Gulp

Now that we have set up the Vue.js configuration and applied it to our Razor view we will need to run Gulp to execute what we have set in our gulpfile.现在我们已经设置了 Vue.js 配置并将其应用于我们的 Razor 视图,我们需要运行 Gulp 来执行我们在 gulpfile 中设置的内容。 Like in step 2 go to your root folder and open a command prompt then execute the command 'npm run dev', again without the quotes.就像在第 2 步中一样,转到您的根文件夹并打开命令提示符,然后执行命令“npm run dev”,再次不带引号。

  1. Run

Now for the final step run your ASP.NET Core MVC app and check the console of your web browser.最后一步,运行 ASP.NET Core MVC 应用程序并检查 Web 浏览器的控制台。 You should now be able to see the message we set in step 5.您现在应该能够看到我们在步骤 5 中设置的消息。

(I wrote the guide in the blog post for reference whenever I may need it :D) (我在博客文章中写了该指南以供我需要时参考:D)

I created this template that combines .NET MVC with Vue.js .我创建了这个结合了.NET MVCVue.js的模板。 You can use the entire Vue ecosystem but if you don't want it on any page you can just opt out.您可以使用整个 Vue 生态系统,但如果您不希望它出现在任何页面上,您可以选择退出。

GitHub: https://github.com/danijelh/aspnetcore-vue-typescript-template GitHub: https ://github.com/danijelh/aspnetcore-vue-typescript-template

Medium: https://medium.com/@danijelhdev/multi-page-net-core-with-vue-js-typescript-vuex-vue-router-bulma-sass-and-webpack-4-efc7de83fea4中: https ://medium.com/@danijelhdev/multi-page-net-core-with-vue-js-typescript-vuex-vue-router-bulma-sass-and-webpack-4-efc7de83fea4

You can use it as an example or starting point.您可以将其用作示例或起点。

I found a way to create single file Vue Components in ASP.NET Core Web App by storing them as shared Razor Views and referencing as Partials in the project.我找到了一种在 ASP.NET Core Web App 中创建单个文件 Vue 组件的方法,方法是将它们存储为共享的 Razor 视图并在项目中作为 Partials 引用。 This way does not require using of any JavaScript Bundles It is a very simple solution and works perfectly with Vue v2.6.x.这种方式不需要使用任何 JavaScript Bundles 这是一个非常简单的解决方案,并且与 Vue v2.6.x 完美配合。

Here is a simple single file Bootstrap Card Vue component ( _Card.cshtml ).这是一个简单的单文件 Bootstrap Card Vue 组件 ( _Card.cshtml )。

<style>
    .card {
        width: 15rem;
    }
</style>
<script type="text/javascript">
    Vue.component('vue-card', {
        props: {
            id: String,
            name: String,
            img: String
        },
        template: '#vue-card-template'
    });
</script>
<script type="text/template" id="vue-card-template">
    <div v-bind:id="id" v-bind:name="name">
        <div class="card">
            <img v-bind:src="img" class="card-img-top p-4 bg-light border-bottom">
            <div class="card-body">
                <p class="card-text">
                    <slot></slot>
                </p>
            </div>
        </div>
    </div>
</script>

And this is the part using it on a Razor Page:这是在 Razor 页面上使用它的部分:

<div id="app">
    <vue-card id="Id" name="Card" img="https://vuejs.org/images/logo.png" class="mb-4">
         <h6>Bootstrap 4 Card Vue Component</h6>
       </vue-card>
</div>

@section Scripts {

<partial name="_Card" />

<script type="text/javascript">
        var app = new Vue({
            el: '#app'
        })
</script>
}

Please check my sample project on Github for details: ASP.NET Core + Vue.js详情请查看我在 Github 上的示例项目: ASP.NET Core + Vue.js

I also wrote an article about my way of Using Vue Components in ASP.NET Core at Medium.我还在 Medium 上写了一篇关于我在 ASP.NET Core 中使用 Vue 组件的方式的文章。

I too am late to this party but I believe a lot has changed in the last year or less.我参加这个聚会也迟到了,但我相信在过去一年或更短的时间里发生了很多变化。 Given that the ES6 module spec (and also dynamic modules) now has relatively broad browser support (see CanIUse ), the options for integrating Vue.js into ASP.NET MVC Razor views are now far, far better.鉴于 ES6 模块规范(以及动态模块)现在具有相对广泛的浏览器支持(请参阅CanIUse ),将 Vue.js 集成到 ASP.NET MVC Razor 视图中的选项现在要好得多。 One thing I've learned about Vue.js is it's best to drop preconceptions about "plug-ins", in the jQuery sense.我从 Vue.js 中学到的一件事是,最好放弃对 jQuery 意义上的“插件”的先入之见。 If you're like me and come from the jQuery world (no Angular or React experience), you must sit down and learn Vue's component model (even SFCs; though you don't need them in this case, they help define the big picture).如果你像我一样来自 jQuery 世界(没有 Angular 或 React 经验),你必须坐下来学习 Vue 的组件模型(甚至是 SFC;虽然在这种情况下你不需要它们,但它们有助于定义全局)。 This requires a decent grasp of ES6 (ECMAScript 2015).这需要很好地掌握 ES6(ECMAScript 2015)。

The iterative and incremental approach is, if you want to start learning and leveraging one of Vue's greatest assets (ease of CDD - component driven development), then simply add the "Full" build (see guide ) in the script tag.迭代和增量方法是,如果您想开始学习和利用 Vue 的最大资产之一(易于 CDD - 组件驱动开发),那么只需在脚本标签中添加“完整”构建(参见指南)。 Using ES6 module syntax (import/export) you can build your own library of components that plug in anywhere you need them;使用 ES6 模块语法(导入/导出),您可以构建自己的组件库,这些组件库可以在您需要的任何地方插入; no Webpack or transpiling required.不需要 Webpack 或转译。 This is truly an awesome development because you can dabble in Vue.js, using best practices for componentization, without taking on an initial (onerous) learning curve of adding Webpack and Babel to your .NET project.这确实是一个很棒的开发,因为您可以涉足 Vue.js,使用组件化的最佳实践,而无需承担将 Webpack 和 Babel 添加到您的 .NET 项目的初始(繁重)学习曲线。 And, as an added bonus, later on when you need to up your game with modern tooling and workflows (NPM, Webpack, testing, HMR, VS Code, etc), you have many of your components tested and ready to go.而且,作为额外的奖励,稍后当您需要使用现代工具和工作流程(NPM、Webpack、测试、HMR、VS Code 等)来提升您的游戏时,您的许多组件都经过测试并准备就绪。

Essentially you build and attach root Vue instances (aka Vue components) to elements in the DOM.本质上,您构建并附加根 Vue 实例(也称为 Vue 组件)到 DOM 中的元素。 Once you understand that everything is a component then you gain confidence in digging into open-source packages like vue-moment and vue-datetime-picker, and importing them via module syntax or learning from them to incorporate into your own custom components.一旦你明白一切都是一个组件,那么你就会有信心深入研究像 vue-moment 和 vue-datetime-picker 这样的开源包,并通过模块语法导入它们或学习它们以合并到你自己的自定义组件中。

I spent a long time learning how to use Browserify and Babel so I could set up my own ES6 environments.我花了很长时间学习如何使用 Browserify 和 Babel,以便建立自己的 ES6 环境。 However, when it comes to using Vue I'm quite happy to go with the default templates, which are best accessed by installing Vue-CLI .但是,在使用 Vue 时,我很乐意使用默认模板,最好通过安装Vue-CLI来访问这些模板。 You can choose between Browserify and Webpack, and either simple setups or full on with linting, unit tests and Single-File Components using the runtime-only version.您可以在 Browserify 和 Webpack 之间进行选择,也可以选择简单的设置,也可以使用仅运行时版本进行完整的 linting、单元测试和单文件组件。

It just works.它只是工作。

This question is a bit old but..这个问题有点老但是..

I have a little sample project on GitHub that uses ASP.NET and Vue.js.我在GitHub 上有一个使用 ASP.NET 和 Vue.js 的小示例项目。 It uses Yarn (or npm) as a package manager and Webpack.它使用 Yarn(或 npm)作为包管理器和 Webpack。

It is not .NET Core, but the way of using it will be the same.它不是 .NET Core,但使用它的方式是一样的。 It might help you get started.它可能会帮助您入门。

The strange file structure is because it runs on our Sitecore CMS system.奇怪的文件结构是因为它运行在我们的 Sitecore CMS 系统上。

Hope it helps.希望能帮助到你。

If you are in 2022 or a bit later, I think, you have to take a look at ServiceStack Project Templates: https://docs.servicestack.net/templates-overview如果您在 2022 年或更晚,我认为您必须查看 ServiceStack 项目模板: https://docs.servicestack.net/templates-overview

To install:安装:

dotnet tool install --global x dotnet 工具安装 --global x

Or install on Apple's new M1 Pro and M1 Max ARM chips with:或者安装在 Apple 的新 M1 Pro 和 M1 Max ARM 芯片上:

dotnet tool install -g -a x64 x dotnet 工具安装 -g -a x64 x

After that you can check the list of available templates with:之后,您可以使用以下命令检查可用模板列表:

x new x 新的

Or simply get your vue + .net core template by:或者简单地通过以下方式获取您的 vue + .net 核心模板:

x new vue-lite-corefx [ProjectName] x 新的 vue-lite-corefx [项目名称]

The best step-by-step tutorial for integrating Vue.js with ASP.NET Core is given here:此处提供了将 Vue.js 与 ASP.NET Core 集成的最佳分步教程:

https://ourtechroom.com/tech/integrating-vuejs-in-aspnetcore-application/ https://ourtechroom.com/tech/integrating-vuejs-in-aspnetcore-application/

I have posted here a GitHub sample project:我在这里发布了一个 GitHub 示例项目:

https://github.com/Diwas777/integrating-vue-with-asp.net-core-project https://github.com/Diwas777/integrating-vue-with-asp.net-core-project

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 Vue.JS 和 Axios 在 Asp.Net Core 中发布错误 - Error Posting in Asp.Net Core with Vue.JS and Axios 如何使用Identity Server 4保护Asp.net核心2.1和Vue.js单页面应用程序 - How to protect Asp.net core 2.1 and Vue.js single page application with Identity Server 4 带有Vue.js的ASP.NET Core不接受我的纯js组件 - ASP.NET Core with Vue.js doesn't accept my pure js component Vue.js 组件只在asp.net core 中保存模板后才渲染 - Vue.js component only rendering after saving the template in asp.net core 如何下载具有特定名称的文件,在 .NET Core controller 方法中设置,使用 Vue.js? - How to download file with certain name, set in .NET Core controller method, using Vue.js? 如何在 Vue.js Express 应用程序中设置路由参数 - How to set up route parameters in Vue.js Express app 如何在 vue.js 组件中设置方法? - How to set up methods in vue.js components? 使用vue.js,如何设置嵌入式子级的动态路由器链接? - With vue.js, how can I set up a dynamic router-link with embedded children? 如何在Laravel项目中设置Vue.js? - How can I set up Vue.js in my Laravel Project ? Gridsome/Vue.js:如何减少核心包的大小? - Gridsome/Vue.js: How do I reduce the core bundle size?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM