ASP.NET Core 与 Vue.js 服务端渲染
http://mgyongyosi.com/2016/Vuejs-server-side-rendering-with-aspnet-core/
原作者:Mihály Gyöngyösi
译者:oopsguy.com
我真的很喜欢使用 Vue.js 来做前端,Vue 服务端渲染直到第二个版本才被支持。在本例中,我想展示如何将 Vue.js 2 服务端渲染功能整合到 ASP.NET Core 项目中。我们在服务端使用了 Microsoft.AspNetCore.SpaServices 包,该包提供 ASP.NET Core API,以便于我们可以使用上下文信息来调用 Node.js 托管的 JavaScript 代码,并将生成的 HTML 字符串注入渲染页面。
在此示例中,应用程序将展示一个消息列表,服务端只渲染最后两条消息(按日期排序)。可以通过点击“获取消息”按钮从服务端下载剩余的消息。
项目结构如下所示:
.
├── VuejsSSRSample
| ├── Properties
| ├── References
| ├── wwwroot
| └── Dependencies
├── Controllers
| └── HomeController.cs
├── Models
| ├── ClientState.cs
| ├── FakeMessageStore.cs
| └── Message.cs
├── Views
| ├── Home
| | └── Index.cshtml
| └── _ViewImports.cshtml
├── VueApp
| ├── components
| | ├── App.vue
| | └── Message.vue
| ├── vuex
| | ├── actions.js
| | └── store.js
| ├── app.js
| ├── client.js
| ├── renderOnServer.js
| └── server.js
├── .babelrc
├── appsettings.json
├── Dockerfile
├── packages.json
├── Program.cs
├── project.json
├── Startup.cs
├── web.config
├── webpack.client.config.js
└── webpack.server.config.js
如你所见,Vue 应用放置于 VueApp 文件夹下,它有两个组件、一个包含了一个 mutation 和一个 action 的简单 Vuex store 和一些我们接下来要讨论的文件:app.js、client.js、renderOnServer.js、server.js。
实现 Vue.js 服务端渲染

要使用服务端渲染,我们必须在 Vue 应用中创建两个不同的 bundle:一个用于服务端(由 Node.js 运行),另一个将在浏览器中运行并在客户端上混合应用。
app.js
引导此模块中的 Vue 实例。它被两个 bundle 使用。
import Vue from 'vue';
import App from './components/App.vue';
import store from './vuex/store.js';
const app = new Vue({
store,
...App
});
export { app, store };
server.js
该服务端 bundle 的入口点导出一个函数,该函数有一个 context 属性,可用于从渲染调用中推送任何数据。
client.js
客户端 bundle 的入口点,其使用了一个名为 INITIAL_STATE 的全局 Javascript 对象(该对象将由预渲染模块创建)替换 store 的当前状态,并将应用挂载到指定的元素(.my-app)。
import { app, store } from './app';
store.replaceState(__INITIAL_STATE__);
app.$mount('.my-app');
Webpack 配置
要创建 bundle,我们必须添加两个 Webpack 配置文件(一个用于服务端,一个用于客户端构建),不要忘了安装 Webpack,如果你还没有安装,请执行:npm install -g webpack。
webpack.server.config.js
const path = require('path');
module.exports = {
target: 'node',
entry: path.join(__dirname, 'VueApp/server.js'),
output: {
libraryTarget: 'commonjs2',
path: path.join(__dirname, 'wwwroot/dist'),
filename: 'bundle.server.js',
},
module: {
loaders: [
{
test: /\.vue$/,
loader: 'vue',
},
{
test: /\.js$/,
loader: 'babel',
include: __dirname,
exclude: /node_modules/
},
{
test: /\.json?$/,
loader: 'json'
}
]
},
};
webpack.client.config.js
const path = require('path');
module.exports = {
entry: path.join(__dirname, 'VueApp/client.js'),
output: {
path: path.join(__dirname, 'wwwroot/dist'),
filename: 'bundle.client.js',
},
module: {
loaders: [
{
test: /\.vue$/,
loader: 'vue',
},
{
test: /\.js$/,
loader: 'babel',
include: __dirname,
exclude: /node_modules/
},
]
},
};
运行 webpack --config webpack.server.config.js,如果运行成功,则你可以在 /wwwroot/dist/bundle.server.js 找到服端的 bundle。要获取客户端 bundle,请运行 webpack --config webpack.client.config.js,相关输出可以在 /wwwroot/dist/bundle.client.js 中找到。
实现 Bundle Render
该模块将由 ASP.NET Core 执行,它负责:
- 渲染我们之前创建的服务端 bundle
- 将 window.__ INITIAL_STATE__ 设置为从服务端发送的对象
process.env.VUE_ENV = 'server';
const fs = require('fs');
const path = require('path');
const filePath = path.join(__dirname, '../wwwroot/dist/bundle.server.js')
const code = fs.readFileSync(filePath, 'utf8');
const bundleRenderer = require('vue-server-renderer').createBundleRenderer(code)
module.exports = function (params) {
return new Promise(function (resolve, reject) {
bundleRenderer.renderToString(params.data, (err, resultHtml) => { // params.data is the store's initial state. Sent by the asp-prerender-data attribute
if (err) {
reject(err.message);
}
resolve({
html: resultHtml,
globals: {
__INITIAL_STATE__: params.data // window.__INITIAL_STATE__ will be the initial state of the Vuex store
}
});
});
});
};
实现 ASP.NET Core 部分
如之前所述,我们使用了 Microsoft.AspNetCore.SpaServices 包,它提供了一些 TagHelper,可轻松调用 Node.js 托管的 Javascript(在后台,SpaServices 使用 Microsoft.AspNetCore.NodeServices 包来执行 Javascript)。
Views/_ViewImports.cshtml
为了使用 SpaServices 的 TagHelper,我们需要将它们添加到 _ViewImports 中。
@addTagHelper "*, Microsoft.AspNetCore.SpaServices"
Home/Index
public IActionResult Index()
{
var initialMessages = FakeMessageStore.FakeMessages.OrderByDescending(m => m.Date).Take(2);
var initialValues = new ClientState() {
Messages = initialMessages,
LastFetchedMessageDate = initialMessages.Last().Date
};
return View(initialValues);
}
它从 MessageStore(仅用于演示目的的一些静态数据)中获取两条最新的消息(按日期倒序排序),并创建一个 ClientState 对象,该对象将被用作 Vuex store 的初始状态。
Vuex store 默认状态:
const store = new Vuex.Store({
state: { messages: [], lastFetchedMessageDate: -1 },
// ...
});
ClientState 类:
public class ClientState
{
[JsonProperty(PropertyName = "messages")]
public IEnumerable<Message> Messages { get; set; }
[JsonProperty(PropertyName = "lastFetchedMessageDate")]
public DateTime LastFetchedMessageDate { get; set; }
}
Index View
最后,我们有了初始状态(来自服务端)和 Vue 应用,所以只需一个步骤:使用 asp-prerender-module 和 asp-prerender-data TagHelper 在视图中渲染 Vue 应用的初始值。
@model VuejsSSRSample.Models.ClientState
<!-- ... -->
<body>
<div class="my-app" asp-prerender-module="VueApp/renderOnServer" asp-prerender-data="Model"></div>
<script src="~/dist/bundle.client.js" asp-append-version="true"></script>
</body>
<!-- ... -->
asp-prerender-module 属性用于指定要渲染的模块(在本例中为 VueApp/renderOnServer)。我们可以使用 asp-prerender-data 属性指定一个将被序列化并发送到模块的默认函数作为参数的对象。
你可以从以下地址下载原文的示例代码:
http://github.com/mgyongyosi/VuejsSSRSample
ASP.NET Core 与 Vue.js 服务端渲染的更多相关文章
- NET Core 与 Vue.js 服务端渲染
NET Core 与 Vue.js 服务端渲染 http://mgyongyosi.com/2016/Vuejs-server-side-rendering-with-aspnet-core/原作者: ...
- Vue.js 服务端渲染业务入门实践
作者:威威(沪江前端开发工程师) 本文原创,转载请注明作者及出处. 背景 最近, 产品同学一如往常笑嘻嘻的递来需求文档, 纵使内心万般拒绝, 身体倒是很诚实. 接过需求,好在需求不复杂, 简单构思 后 ...
- vue.js 服务端渲染nuxt.js反向代理nginx部署
vue.js的官方介绍里可能提到过nuxt.js,我也不太清楚我怎么找到这个的 最近项目vue.js是主流了,当有些优化需求过来后,vue还是有点力不从心, 比如SEO的优化,由于vue在初始化完成之 ...
- 追求极致的用户体验ssr(基于vue的服务端渲染)
首先这篇博客并不是ssr建议教程,需要ssr入门的我建议也不要搜索博客了,因为官网给出了详细的入门步骤,只需要step by step就可以了,这篇博客的意义是如何使用ssr,可能不同的人有不同的意见 ...
- Nuxt.js服务端渲染实践,从开发到部署
感悟 经过几个周六周日的尝试,终于解决了服务端渲染中的常见问题,当SEO不在是问题的时候,或许才是我们搞前端的真正的春天,其中也遇到了一些小坑,Nuxt.js官方还是很给力的,提issue后很积极的给 ...
- vue ssr服务端渲染
SSR:Server Side Rendering(服务端渲染) 目的是为了解决单页面应用的 SEO 的问题,对于一般网站影响不大,但是对于论坛类,内容类网站来说是致命的,搜索引擎无法抓取页面相关内容 ...
- asp.net core系列 74 Exceptionless服务端安装
一. Docker安装 Docker 要求版本Docker 18.09.0+以上 安装地址:https://www.runoob.com/docker/windows-docker-insta ...
- nuxt.js服务端渲染中less的配置和使用
第一步:npm 安装 less 和 less-loader ,文件根目录下安装,指令如下 npm install less less-loader --save-dev 第二步:直接在组件中使用 &l ...
- Vue.js与 ASP.NET Core 服务端渲染功能整合
http://mgyongyosi.com/2016/Vuejs-server-side-rendering-with-aspnet-core/ 原作者:Mihály Gyöngyösi 译者:oop ...
随机推荐
- 关于el-dialog,我更推荐的用法
最近的项目里用上了vue和element-ui.vue这种轻量级渐进式框架的舒适自不必说,但一直困扰着我的,是如何方便又优雅的弹出模态dialog... 对于我这种在jquery出现之前就用docum ...
- cannot be cast to javax.servlet.Servlet
在第一次开发Maven项目时,maven环境和仓库以及eclipse都和讲师讲解的一样,可是却遇到下面这个问题: java.lang.ClassCastException: servlet.UserS ...
- php根据ip段以及子网掩码,判断某ip是否处于某子网下
为了检测客户端ip是否位于指定的网络里(如防火墙过滤有时候需要用到这个技术),有如下方法: 1.第一种 public function netMatch($client_ip, $server ...
- Python自学笔记-paramiko模块(Mr serven)
文章出处:http://www.cnblogs.com/wupeiqi/articles/5095821.html SSHClient 用于连接远程服务器并执行基本命令 基于用户名密码连接: #!/u ...
- 【转】wireshark基本用法及过虑规则
Wireshark 基本语法,基本使用方法,及包过虑规则: 1.过滤IP,如来源IP或者目标IP等于某个IP 例子: ip.src eq 192.168.1.107 or ip.dst eq 19 ...
- 学习Ajax
1.XHR对象 IE7+.Firefox.Opera.Chrome和Safari都支持原生XMLHttpRequest对象,IE6不支持,只支持ActiveXObject对象,该对象在IE11中已经不 ...
- 【完美解决】2017打开MVC 4项目,cshtml页面提示‘当前上下文不存在名称model’
时间:2017/10/19 背景:领导让再之前的MVC 4老项目上新增功能,从GIT上拉取下来,使用VS2017打开之后,cshtml界面所有和Razor相关的代码均被提示‘当前上下文不存在名称XXX ...
- win10 uwp 绘图 Line 控件使用
本文主要讲一个在绘图中,我们会有一个基础的控件,Line.控件的基本使用和他能做出的我们很多时候需要的界面. 虽然是一个简单控件,但是可以做出很诡异的很好看的UI. 首先,我们要知道,Line就是画直 ...
- 在 JPA、Hibernate 和 Spring 中配置 Ehcache 缓存
jpa, hibernate 和 spring 时配置 ehcache 二级缓存的步骤. 缓存配置 首先在 persistence.xml 配置文件中添加下面内容: <property name ...
- Struts2运行流程-源码剖析
本文为原创,如需转载,请标明出处:http://www.cnblogs.com/gudu1/p/7726172.html 首先说一下查看这些框架源码的感受,每一次深入探究 Spring.Struts ...