在前端使用 Vue.js,Vue 服务端渲染直到第二个版本才被支持。 在本例中,我想展示如何将 Vue.js 服务端渲染功能整合 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 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

asp-prerender-module属性用于指定要渲染的模块(在我们的例子中为VueApp/renderOnServer)。我们可以使用 asp-prerender-data属性指定一个将被序列化并发送到模块的默认函数作为参数的对象。

您可以从以下地址下载原文的示例代码:

http://github.com/mgyongyosi/VuejsSSRSample

相关推荐:

php和asp渲染页面,Vue.js与 ASP.NET Core 服务端渲染功能相关推荐

  1. 基于vue的nuxt框架cnode社区服务端渲染

    nuxt-cnode 基于vue的nuxt框架仿的cnode社区服务端渲染,主要是为了seo优化以及首屏加载速度 线上地址 http://nuxt-cnode.foreversnsd.cn githu ...

  2. vue添加html开启服务器_vue服务端渲染添加缓存

    虽然 Vue 的服务器端渲染(SSR)相当快速,但是由于创建组件实例和虚拟 DOM 节点的开销,无法与纯基于字符串拼接(pure string-based)的模板的性能相当.在 SSR 性能至关重要的 ...

  3. 【服务端渲染】之 Vue SSR

    前言 笔记来源:拉勾教育 大前端高薪训练营 阅读建议:内容较多,建议通过左侧导航栏进行阅读 Vue SSR 基本介绍 Vue SSR 是什么 官方文档:https://ssr.vuejs.org/ V ...

  4. 服务端渲染(SSR)和Nuxt.js

    服务端渲染(SSR) 客户端渲染和传统服务端渲染的问题 SPA应用有两个非常明显的问题: 首屏渲染慢 不利于 SEO 传统的服务端渲染又存在: 应用的前后端部分完全耦合在一起,在前后端协同开发方面会有 ...

  5. 服务端渲染和客户端渲染以及服务器部署

    文章内容输出来源:拉勾教育前端高薪训练营 SPA单页面应用 优点 用户体验好 开发效率高 渲染性能好 可维护性好 缺点 需等待客户端js解析执行完,造成首屏渲染时间长 单页面的html是没有内容的,不 ...

  6. 搭建自己的 服务端渲染 SSR

    一.VUE SSR是什么 官方文档:https://ssr.vuejs.org/ Vue SSR(Vue.js Server-Side Rendering) 是 Vue.js 官方提供的一个服务端渲染 ...

  7. Vuex 数据流管理及Vue.js 服务端渲染(SSR)

    Vuex 数据流管理及Vue.js 服务端渲染(SSR)项目见:https://github.com/smallSix6/fed-e-task-liuhuijun/tree/master/fed-e- ...

  8. Nuxt --- 也来说说vue服务端渲染

    Nuxt 随着现在vue和react的流行,许多网站都做成了SPA,确实提升了用户体验,但SPA也有两个弱点,就是SEO和首屏渲染速度.为了解决单页应用的痛点,基于vue和react的服务端渲染应运而 ...

  9. 使用Nuxt.js框架开发(SSR)服务端渲染项目

    (SSR)服务端渲染的优缺点 优点: 1.前端耗时少,首屏加载速度快.因为后端拼接完了html,浏览器只需要直接渲染出来. 2.有利于SEO.因为在后端有完整的html页面,所以爬虫更容易爬取获得信息 ...

最新文章

  1. python工程计算软件库_python中常用的科学计算工具包
  2. STL源码剖析——P142关于list::sort函数
  3. 等待多线程完成的CountDownLatch
  4. maven的pom.xml中profiles的作用
  5. 金融时报:人工智能在银行中的应用—对全球30家大型银行的调查
  6. 编程关键词介绍...
  7. OpenSea2月总交易额为9390.4万美元 用户总数突破5万人
  8. 孩子有心理问题不愿意做心理咨询,父母该怎么办?
  9. hdu 3905(dp)
  10. 一条汇编指令是如何在计算机的硬件中进行执行的
  11. BZOJ3997 TJOI2015组合数学(动态规划)
  12. Android Studio配置文件修改
  13. 手把手教你搭建FastDFS集群(中)
  14. linux adb工具 终极总结
  15. java读取dbf数据类型,读取foxpro格式的dbf文件-JSP教程,Java技巧及代码
  16. python drop用法_Python drop方法删除列之inplace参数实例
  17. MongoTemplate根据时间查询的大坑
  18. Spec文件中判断是升级or卸载
  19. 微软亚洲研究院 (MSRA) 的实习体验如何?
  20. 阿里云系统导出到本地虚拟机

热门文章

  1. 1.12_count_sort_计数排序
  2. spring boot 核心_Spring Boot 的 10 个核心模块
  3. linux系统可以安装搜狗输入法,在Arch Linux系统中安装搜狗输入法的方法
  4. node 升级_那些修改node_modules的骚操作
  5. HDU - 1043 Eight (A*搜索)
  6. python把源代码打包成.exe文件
  7. OSi七成模型 tcp/ip网络模型
  8. php中如何使用html代码
  9. 游戏编程编程学习推荐
  10. 如何设置VSCode中文显示