Javascript 如何设置 ASP.NET Core + Vue.js?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39478855/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:36:44  来源:igfitidea点击:

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

javascriptasp.net-coreasp.net-core-mvcvue.js

提问by Gerardo Grignoli

I need to integrate Vue.js with some ASP.NET Core MVC views. I picked Vue.js over other alternatives because it seemed to be simpler – "just add it via a <script>tag", they said. No need to learn Gulp/Grunt/Webpack/Browserify/etc.

我需要将 Vue.js 与一些 ASP.NET Core MVC 视图集成。我选择 Vue.js 而不是其他替代品,因为它看起来更简单——“只需通过<script>标签添加它”,他们说。无需学习 Gulp/Grunt/Webpack/Browserify/等。

That turned out to be false. At my first attempt to handle dates I tried some extensions like vue-momentand vue-datetime-picker, taken from this official curated list of awesome things related to Vue.jsbut I hit a wall here. While the first does not mandate using the require()JS syntax (CommonJS?), the second one doesn't work without it. Other extensions happen to 'use babel'and imports/exportswhich is ECMAScript 6 that needs to be compiled. So, most Vue.js libraries and toolings indeed need a compiler, plus the require()syntax, and all that stuff from the Node world?

结果证明这是错误的。在我第一次尝试处理日期时,我尝试了一些扩展,比如vue-momentvue-datetime-picker,取自这个官方策划的与 Vue.js 相关的很棒的东西的列表,但我在这里碰壁了。虽然第一个不要求使用require()JS 语法(CommonJS?),但第二个没有它就不能工作。其他扩展发生在'use babel'imports/exports这是需要编译的 ECMAScript 6。那么,大多数 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 应用程序?

回答by Gerardo Grignoli

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. 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,因为它比其他替代方案更简单。更少的仪式,更少的样板,更少的代码。它被称为渐进式框架......对!但仅限于一点。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 LOTof stuff. (Configuring bundler, npm+package dependencies hell, ES6 stuff.)
  • You do not want to make a bleeding-edge single-page application. Embedding Vue.js inside a few HTML pages seems enough.
  • HTTP/2 is becoming mainstream, so bundlers like Webpack or Browserify will provide fewer benefits, at least on performance.
  • EventuallyES6 modules will be supported directly in the browser, so we won't need to build whatever the latestJavaScript is into browser-compatibleJavaScript.
  • 你没有多少天可以学习很多东西。(配置捆绑器,npm+package 依赖地狱,ES6 的东西。)
  • 您不想制作一个前沿的单页应用程序。在几个 HTML 页面中嵌入 Vue.js 似乎就足够了。
  • HTTP/2 正在成为主流,因此像 Webpack 或 Browserify 这样的打包器将提供更少的好处,至少在性能方面。
  • 最终,浏览器将直接支持 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.
  • Only use browser-ready JavaScript libraries. 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/exportstatements are written in ES6 so avoid them too.
  • Use Bower to download browser-ready libs. Avoid NPM (which implies having a module system in place).
  • 只需使用<script>标签添加 JS 库。
  • 仅使用浏览器就绪的 JavaScript 库。使用require()或 UMD 前缀的代码(function (root, factory) {要求您设置模块(因此除非您设置了 CommonJS,否则它不是浏览器就绪的)。带有import/export语句的JS 文件是用 ES6 编写的,所以也要避免它们。
  • 使用 Bower 下载浏览器就绪的库。避免 NPM(这意味着有一个模块系统就位)。

Caveat: You will not be able to use advanced Vue.js features like single-file componentsor Vue Router, but that is OK. You will have to do a few things manually.

警告:您将无法使用高级 Vue.js 功能,例如单文件组件或 Vue Router,但没关系。您将不得不手动执行一些操作。

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. Browserify also works, but I haven't tried it.

准备几天学习而不是编码。我只会简单地解释一下 Webpack 是如何为我工作的。Browserify 也能用,但我没试过。

I recommend you spend some time learning what JavaScript modules are. Then learn to build them and pack them: I used Webpack. Its documentation is not great, so what worked for me was to follow its tutorialstep by step.

我建议您花一些时间了解什么是JavaScript 模块。然后学习构建它们并打包它们:我使用了 Webpack。它的文档不是很好,所以对我有用的是一步一步地遵循它的教程

At this point, you may have heard that Webpack ALSO has a built-in web server with "hot module reloading". This is a web server for static files to be used only for development. Its benefit is that whenever you edit a JS module, the browser will automatically apply the change without refreshing. This is a very nice, but optional, feature. The problem: this built-in web-server competes with our web server (Kestrel). So, if you want to try this feature during development use the Webpack ASP.NET Core middlewareprovided at Microsoft's JavaScriptServices repo. There you will find the WebApplicationBasic templatethat I am currently using. I dissected it, removed most of its parts and by trying to use it I slowly understood what each part was originally for.

说到这里,你可能已经听说 Webpack 还内置了一个带有“热模块重载”的 web 服务器。这是一个用于静态文件的 Web 服务器,仅用于开发。它的好处是每当你编辑一个 JS 模块时,浏览器会自动应用更改而无需刷新。这是一个非常好的但可选的功能。问题:这个内置的网络服务器与我们的网络服务器(Kestrel)竞争。因此,如果您想在开发期间尝试此功能,请使用Microsoft 的JavaScriptServices 存储库中提供的Webpack ASP.NET Core 中间件。在那里您将找到我当前使用的WebApplicationBasic 模板。我解剖了它,移除了它的大部分部分,通过尝试使用它,我慢慢地理解了每个部分的最初用途。

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.
  • Built-in production mode: Creates small minified files. Useful for ‘dotnet publish'.
  • 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. The compilation output is not written to disk and only kept in memory and served via HTTP. The JavaScriptServices middleware forwards requests from Kestrel to Webpack's web server to make this work.
  • 内置开发模式:创建大文件,便于调试。将它与 'watch-mode' 一起使用,这样每当你修改一个文件时,就会触发一个新的 Webpack 构建。
  • 内置生产模式:创建小的缩小文件。对“dotnet 发布”很有用。
  • 使用 Webpack 的 Web 服务器和热模块重新加载与 Webpack ASP.NET Core 中间件意味着您的应用程序将在后台运行 Webpack,构建并观察源文件的更改。编译输出不会写入磁盘,只会保存在内存中并通过 HTTP 提供服务。JavaScriptServices 中间件将来自 Kestrel 的请求转发到 Webpack 的 Web 服务器以完成这项工作。

Whatever Webpack config you go with, you have to include ‘vue-loader' in your Webpack config. You may be inspired by Vue's webpack-simple template.

无论您使用哪种 Webpack 配置,您都必须在 Webpack 配置中包含“vue-loader”。你可能会受到Vue 的 webpack-simple template 的启发。

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.

我还没有涵盖我想要的所有内容,但是这个主题太广泛了,我需要回到编码。请留下一些反馈。

回答by Norbert Norbertson

I'm late to the party but there is now a template available for .NET Core that you can build with a single command. 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 的模板,您可以使用单个命令构建它。在安装了 .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. Just open the project in VS or VS Code and you're away.

在几毫秒内,一个完整的新 Vue.js 单页 Web 应用程序使用可运行的 .NET Core 后端和控制器、视图等构建。这太棒了。只需在 VS 或 VS Code 中打开项目即可。

There are also templates for Aurelia, Angular, Knockout and 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!

还有用于 Aurelia、Angular、Knockout 和 React 的模板!您可以将它们全部构建并比较它们如何解决相同的问题。Angular 甚至可以开箱即用地进行服务器端预渲染!

I know .NET Core has a way to go but it's becoming more and more awesome by the day!

我知道 .NET Core 有很长的路要走,但它一天比一天变得越来越棒!

回答by n3n7

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). However, you also mention using Babel and the ES6 modules feature. 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! 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.

您询问是否通过<script>标签包含 Vue (在这种情况下是 CDN 构建)。但是,您还提到了使用 Babel 和 ES6 模块功能。在这种情况下,我建议将 Webpack 用于客户端应用程序,它将使用 Babel 编译您的 ES6,允许您使用模块和组件,并使用模板!您还可以获得热模块重新加载(编辑您的源代码并实时查看客户端应用程序中的更改!)并且 Webpack 会将您的 SPA 捆绑到一个静态 HTML5 应用程序中。

The official Vue.js docs point to their own Webpack template.

官方 Vue.js 文档指向他们自己的 Webpack 模板

So you canrun 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 JavaScriptServiceslets 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; this is just like the standalone server.

他们提供了Angular 2的官方模板,甚至还有一个标有Vue.js的模板,但Vue模板只是官方的Webpack模板,没有与.NET进行任何集成;这就像独立服务器一样。

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. 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. In release mode, .NET Core will use the prebuilt Webpack output. You can find it on GitHub:

我找不到任何为 Vue.js 执行此操作的模板,因此我将示例 ASP.NET Core 应用程序放在一起,该应用程序使用 Vue.js Webpack 应用程序加载 Webpack 开发中间件。当 .NET Core 服务器在开发模式下运行时,您可以编辑 Vue 源代码,更改将通过快速增量补丁反映出来,而无需重新构建整个应用程序。在发布模式下,.NET Core 将使用预构建的 Webpack 输出。你可以在 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. 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.

上面链接的存储库有一个完整的应用程序演示,它使用 NancyFx、axios、Vue.js 和 Vue Material,并且是一个简单的 URL 缩短器。如果您想要更简单的设置步骤,可以轻松添加到现有应用程序中,请查看我的这篇博文

Obligatory disclosure: I wrote that blog post.

强制性披露:我写了那篇博文。

回答by Stanislav

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. It provides a domain layer, repository layer, etc. Note that this is a Yeoman generator and it uses TypeScript. https://github.com/vue-typed/generator-vue-net-core

第一个为您提供具有一些预定义架构的多项目解决方案。这个模板比这里已经提到的 JavaScriptServices 解决方案更接近真实世界的项目。它提供了域层、存储库层等。请注意,这是一个 Yeoman 生成器,它使用 TypeScript。 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. 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. 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. Here's the link: https://github.com/mrellipse/toucan

第二个只是GitHub上的一个项目,如果你想使用它,你应该克隆它。它不是 Yeoman 生成器,我认为这是令人遗憾的,但我发现这个模板中的结构比第一个更好。此外,它还有很多不错的小东西,比如一些异常过滤器,你很可能仍然会这样做。如果您是初学者,这个模板将是天赐之物。这个模板推荐在 awesome-vue 页面。这是链接:https: //github.com/mrellipse/toucan

回答by SlowNinja

You can try the steps below, from this simple guide.

您可以从这个简单的指南中尝试以下步骤。

  1. Set up the npm configuration file (package.json)

Below is the npm package I will use:

{
  "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

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.

  1. Set up Gulp

Once the npm package is installed you may now set up the Gulp file. You will need to add a Gulp configuration file (gulpfile.js). Later on we will create the Vue JS which we will call vueApp.js with the code below. The first argument is the public output directory and the other one is the source directory. For more details on Webpack click here.

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

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'. Now once the folder setup is complete add a new JavaScript file in the ‘js' folder named ‘vueApp.js'.

  1. Start coding in your Vue JS file

You may now start coding. In the example below we will be displaying an alert to indicate that Vue.js is running.

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

Open your layout page and wrap the content of your body tag with a div and an id of ‘app'. 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. Lastly add a reference to the Vue JS file. Be sure to move outside the ‘app' div the script references to prevent error.

  1. 设置 npm 配置文件 (package.json)

下面是我将使用的 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. 安装 npm 包

打开命令提示符并转到应用程序的根文件夹,然后使用命令“npm install”(不带引号)安装从 package.json 文件中设置的 npm 包。

  1. 设置 Gulp

安装 npm 包后,您现在可以设置 Gulp 文件。您需要添加 Gulp 配置文件 (gulpfile.js)。稍后我们将使用以下代码创建 Vue JS,我们将其称为 vueApp.js。第一个参数是公共输出目录,另一个是源目录。有关 Webpack 的更多详细信息,请单击此处

var elixir = require('laravel-elixir');



require('laravel-elixir-vue-2');

elixir(function (mix) {
    mix.webpack('vueApp.js', 'wwwroot/js/dist', 'wwwroot/js');
});
  1. 创建 Vue JS 文件

在您的 ASP.NET Core Web 应用程序项目解决方案资源管理器中,转到 wwwroot 并添加一个“js”文件夹,如果它不存在,则再次添加一个名为“dist”的新文件夹。现在,一旦文件夹设置完成,在名为“vueApp.js”的“js”文件夹中添加一个新的 JavaScript 文件。

  1. 在你的 Vue JS 文件中开始编码

您现在可以开始编码。在下面的示例中,我们将显示一个警报以指示 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. 将 Vue JS 应用到您的 Razor 视图或 HTML

打开你的布局页面并用一个 div 和一个 'app' 的 id 包裹你的 body 标签的内容。我们将使用“app”,因为这是我们在第 5 步的示例代码中使用的 id 标记。名称“app”不是必需的,您可以将其更改为您想要的名称。最后添加对 Vue JS 文件的引用。请务必将脚本引用的“应用程序”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

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. 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.

  1. Run

Now for the final step run your ASP.NET Core MVC app and check the console of your web browser. You should now be able to see the message we set in step 5.

  1. 运行 Gulp

现在我们已经设置了 Vue.js 配置并将其应用于我们的 Razor 视图,我们将需要运行 Gulp 来执行我们在 gulpfile 中设置的内容。就像在第 2 步中一样,转到您的根文件夹并打开命令提示符,然后再次执行命令“npm run dev”,不带引号。

现在进行最后一步,运行 ASP.NET Core MVC 应用程序并检查 Web 浏览器的控制台。您现在应该能够看到我们在步骤 5 中设置的消息。

(I wrote the guide in the blog post for reference whenever I may need it :D)

(我在博客文章中写了指南以供我需要时参考:D)

回答by Diwas Poudel

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

回答by Danijel

I created this template that combines .NET MVCwith Vue.js. You can use the entire Vue ecosystem but if you don't want it on any page you can just opt out.

我创造了这个模板,结合.NET MVCVue.js。您可以使用整个 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.

您可以将其用作示例或起点。

回答by Mark Dalsaso

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. One thing I've learned about Vue.js is it's best to drop preconceptions about "plug-ins", in the jQuery sense. If you're like me and come from the jQuery world (no Angular or React experience), you mustsit down and learn Vue's component model (even SFCs; though you don't need them in this case, they help define the big picture). This requires a decent grasp of ES6 (ECMAScript 2015).

我参加这个聚会也迟到了,但我相信在过去一年或更短的时间内发生了很多变化。鉴于 ES6 模块规范(以及动态模块)现在具有相对广泛的浏览器支持(请参阅CanIUse),将 Vue.js 集成到 ASP.NET MVC Razor 视图的选项现在要好得多。我从 Vue.js 学到的一件事是最好放弃对 jQuery 意义上的“插件”的先入之见。如果你像我一样来自 jQuery 世界(没有 Angular 或 React 经验),你必须坐下来学习 Vue 的组件模型(甚至 SFC;虽然在这种情况下你不需要它们,但它们有助于定义全局)。这需要很好地掌握 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. Using ES6 module syntax (import/export) you can build your own library of components that plug in anywhere you need them; no Webpack or transpiling required. 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. 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.

迭代和增量方法是,如果您想开始学习和利用 Vue 最大的资产之一(CDD 的易用性 - 组件驱动开发),那么只需在脚本标签中添加“完整”构建(参见指南)。使用 ES6 模块语法(导入/导出),您可以构建自己的组件库,可以在您需要的任何地方插入它们;无需 Webpack 或转译。这确实是一个很棒的开发,因为您可以涉足 Vue.js,使用组件化的最佳实践,而无需承担将 Webpack 和 Babel 添加到您的 .NET 项目的初始(繁重)学习曲线。而且,作为一个额外的好处,以后当您需要使用现代工具和工作流程(NPM、Webpack、测试、HMR、VS Code 等)来提升您的游戏时,您的许多组件已经过测试并准备就绪。

Essentially you build and attach root Vue instances (a.k.a. Vue components) to elements in the 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 实例(又名 Vue 组件)并将其附加到 DOM 中的元素。一旦你明白一切都是一个组件,那么你就会有信心挖掘像 vue-moment 和 vue-datetime-picker 这样的开源包,并通过模块语法导入它们或学习它们以合并到你自己的自定义组件中。

回答by CodeHacker

This question is a bit old but..

这个问题有点老了但是..

I have a little sample project on GitHubthat uses ASP.NET and Vue.js. It uses Yarn (or npm) as a package manager and Webpack.

我在GitHub 上有一个使用 ASP.NET 和 Vue.js的小示例项目。它使用 Yarn(或 npm)作为包管理器和 Webpack。

It is not .NET Core, but the way of using it will be the same. It might help you get started.

它不是 .NET Core,但使用方式是一样的。它可能会帮助您入门。

The strange file structure is because it runs on our Sitecore CMS system.

奇怪的文件结构是因为它运行在我们的 Sitecore CMS 系统上。

Hope it helps.

希望能帮助到你。

回答by blues_driven

I spent a long time learning how to use Browserify and Babel so I could set up my own ES6 environments. 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. 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 和 Babel,这样我就可以建立自己的 ES6 环境。但是,在使用 Vue 时,我很乐意使用默认模板,最好通过安装Vue-CLI 来访问这些模板。您可以在 Browserify 和 Webpack 之间进行选择,可以选择简单的设置,也可以使用仅运行时版本的 linting、单元测试和单文件组件。

It just works.

它只是有效。