http://mgyongyosi.com/2016/Vuejs-server-side-rendering-with-aspnet-core/
原作者:Mihály Gyöngyösi
譯者:oopsguy.com
我真的很喜歡在前端使用 Vue.js,Vue 服務端渲染直到第二個版本才被支持。 在本例中,我想展示如何將 Vue.js 服務端渲染功能整合 ASP.NET Core。 我們在服務端使用了 Microsoft.AspNetCore.SpaServices 包,該包提供 ASP.NET Core API,以便於我們可以使用上下文信息調用 Node.js 托管的 JavaScript 代碼,並將生成的 HTML 字符串注入渲染頁面。
在此示例中,應用程序將展示一個消息列表,服務端只渲染最后兩條消息(按日期排序)。可以通過點擊“獲取消息”按鈕從服務端下載剩余的消息。
項目結構如下所示:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
.
├── 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 共同使用。
|
1
2
3
4
5
6
7
8
|
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)。
|
1
2
3
|
import { app, store } from
'./app'
;
store.replaceState(__INITIAL_STATE__);
app.$mount(
'.my-app'
);
|
Webpack 配置
為了創建 bundle,我們必須添加兩個 Webpack 配置文件(一個用於服務端,一個用於客戶端構建),不要忘了安裝 Webpack,如果尚未安裝,則:npm install -g webpack。
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
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__** 設置為從服務端發送的對象
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
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 中。
|
1
2
3
4
5
6
7
8
9
10
11
|
@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 默認狀態:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
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 應用的初始值。
|
1
2
3
4
5
6
7
|
@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
總結
以上所述是小編給大家介紹的Vue.js與 ASP.NET Core 服務端渲染功能整合,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網站的支持!
原文鏈接:https://www.cnblogs.com/oopsguy/p/7837400.html

