Vue.js與 ASP.NET Core 服務(wù)端渲染功能整合
http://mgyongyosi.com/2016/Vuejs-server-side-rendering-with-aspnet-core/
原作者:Mihály Gyöngyösi
譯者:oopsguy.com
我真的很喜歡在前端使用 Vue.js,Vue 服務(wù)端渲染直到第二個(gè)版本才被支持。 在本例中,我想展示如何將 Vue.js 服務(wù)端渲染功能整合 ASP.NET Core。 我們?cè)诜?wù)端使用了 Microsoft.AspNetCore.SpaServices 包,該包提供 ASP.NET Core API,以便于我們可以使用上下文信息調(diào)用 Node.js 托管的 JavaScript 代碼,并將生成的 HTML 字符串注入渲染頁面。
在此示例中,應(yīng)用程序?qū)⒄故疽粋€(gè)消息列表,服務(wù)端只渲染最后兩條消息(按日期排序)。可以通過點(diǎn)擊“獲取消息”按鈕從服務(wù)端下載剩余的消息。
項(xiàng)目結(jié)構(gòu)如下所示:
. ├── 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 應(yīng)用位于 VueApp 文件夾下,它有兩個(gè)組件、一個(gè)包含了一個(gè) mutation 和一個(gè) action 的簡(jiǎn)單 Vuex store 和一些我們接下來要討論的其他文件:app.js、client.js、 renderOnServer.js、server.js。
實(shí)現(xiàn) Vue.js 服務(wù)端渲染
要使用服務(wù)端渲染,我們必須從 Vue 應(yīng)用創(chuàng)建兩個(gè)不同的 bundle:一個(gè)用于服務(wù)端(由 Node.js 運(yùn)行),另一個(gè)用于將在瀏覽器中運(yùn)行并在客戶端上混合應(yīng)用。
app.js
引導(dǎo)此模塊中的 Vue 實(shí)例。它由兩個(gè) 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
此服務(wù)端 bundle 的入口點(diǎn)導(dǎo)出一個(gè)函數(shù),該函數(shù)有一個(gè) context 屬性,可用于從渲染調(diào)用中推送任何數(shù)據(jù)。
client.js
客戶端 bundle 的入口點(diǎn),其用一個(gè)名為 INITIAL_STATE 的全局 Javascript 對(duì)象(該對(duì)象將由預(yù)渲染模塊創(chuàng)建)替換 store 的當(dāng)前狀態(tài),并將應(yīng)用掛載到指定的元素(.my-app)。
import { app, store } from './app'; store.replaceState(__INITIAL_STATE__); app.$mount('.my-app');
Webpack 配置
為了創(chuàng)建 bundle,我們必須添加兩個(gè) Webpack 配置文件(一個(gè)用于服務(wù)端,一個(gè)用于客戶端構(gòu)建),不要忘了安裝 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/ }, ] }, };
運(yùn)行 webpack --config webpack.server.config.js, 如果運(yùn)行成功,則可以在 /wwwroot/dist/bundle.server.js 找到服端 bundle。獲取客戶端 bundle 請(qǐng)運(yùn)行 webpack --config webpack.client.config.js,相關(guān)輸出可以在 /wwwroot/dist/bundle.client.js 中找到。
實(shí)現(xiàn) Bundle Render
該模塊將由 ASP.NET Core 執(zhí)行,其負(fù)責(zé):
渲染我們之前創(chuàng)建的服務(wù)端 bundle
將 **window.__ INITIAL_STATE__** 設(shè)置為從服務(wù)端發(fā)送的對(duì)象
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 } }); }); }); };
實(shí)現(xiàn) ASP.NET Core 部分
如之前所述,我們使用了 Microsoft.AspNetCore.SpaServices 包,它提供了一些 TagHelper,可輕松調(diào)用 Node.js 托管的 Javascript(在后臺(tái),SpaServices 使用 Microsoft.AspNetCore.NodeServices 包來執(zhí)行 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(僅用于演示目的的一些靜態(tài)數(shù)據(jù))中獲取兩條最新的消息(按日期倒序排序),并創(chuàng)建一個(gè) ClientState 對(duì)象,該對(duì)象將被用作 Vuex store 的初始狀態(tài)。
Vuex store 默認(rèn)狀態(tài):
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
最后,我們有了初始狀態(tài)(來自服務(wù)端)和 Vue 應(yīng)用,所以只需一個(gè)步驟:使用 asp-prerender-module 和 asp-prerender-data TagHelper 在視圖中渲染 Vue 應(yīng)用的初始值。
@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 屬性指定一個(gè)將被序列化并發(fā)送到模塊的默認(rèn)函數(shù)作為參數(shù)的對(duì)象。
您可以從以下地址下載原文的示例代碼:
http://github.com/mgyongyosi/VuejsSSRSample
總結(jié)
以上所述是小編給大家介紹的Vue.js與 ASP.NET Core 服務(wù)端渲染功能整合,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
相關(guān)文章
vue根據(jù)進(jìn)入的路由進(jìn)行原路返回的方法
今天小編就為大家分享一篇vue根據(jù)進(jìn)入的路由進(jìn)行原路返回的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-09-09vue.js中Vue-router 2.0基礎(chǔ)實(shí)踐教程
這篇文章主要給大家介紹了關(guān)于vue.js中Vue-router 2.0基礎(chǔ)實(shí)踐的相關(guān)資料,其中包括vue-router 2.0的基礎(chǔ)用法、動(dòng)態(tài)路由匹配、嵌套路由、編程式路由、命名路由以及命名視圖等相關(guān)知識(shí),需要的朋友可以參考借鑒,下面來一起看看吧。2017-05-05vue3父子組件通信、兄弟組件實(shí)時(shí)通信方式
這篇文章主要介紹了vue3父子組件通信、兄弟組件實(shí)時(shí)通信方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-06-06Vue實(shí)現(xiàn)DateRange選擇器的禁選功能
在基于Vue.js構(gòu)建的應(yīng)用程序中,處理日期選擇器是一個(gè)常見的需求,尤其是在涉及到日期范圍的選擇時(shí),Vue提供了多種方式來實(shí)現(xiàn)日期選擇器的功能,并允許我們對(duì)這些組件進(jìn)行高度定制,本文將深入探討如何在Vue應(yīng)用中實(shí)現(xiàn)DateRange選擇器的禁選功能,需要的朋友可以參考下2024-10-10vue3中nextTick()應(yīng)用實(shí)例詳解
這篇文章主要給大家介紹了關(guān)于vue3中nextTick()應(yīng)用的相關(guān)資料,nextTick()等待下一次DOM更新刷新的工具方法,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-12-12vue.js 2.0實(shí)現(xiàn)簡(jiǎn)單分頁效果
這篇文章主要為大家詳細(xì)介紹了vue.js 2.0實(shí)現(xiàn)簡(jiǎn)單分頁效果,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-07-07vue同一個(gè)瀏覽器登錄不同賬號(hào)數(shù)據(jù)覆蓋問題解決方案
同一個(gè)瀏覽器登錄不同賬號(hào)session一致,這就導(dǎo)致后面登錄的用戶數(shù)據(jù)會(huì)把前面登錄的用戶數(shù)據(jù)覆蓋掉,這個(gè)問題很常見,當(dāng)前我這邊解決的就是同一個(gè)瀏覽器不同窗口只能登錄一個(gè)用戶,對(duì)vue同一個(gè)瀏覽器登錄不同賬號(hào)數(shù)據(jù)覆蓋問題解決方法感興趣的朋友一起看看吧2024-01-01Vue?Router路由hash模式與history模式詳細(xì)介紹
Vue?Router是Vue.js官方的路由管理器。它和Vue.js的核心深度集成,讓構(gòu)建單頁面應(yīng)用變得易如反掌。路由實(shí)際上就是可以理解為指向,就是我在頁面上點(diǎn)擊一個(gè)按鈕需要跳轉(zhuǎn)到對(duì)應(yīng)的頁面,這就是路由跳轉(zhuǎn)2022-08-08vue修改swiper框架輪播圖小圓點(diǎn)的樣式不起作用的解決
這篇文章主要介紹了vue修改swiper框架輪播圖小圓點(diǎn)的樣式不起作用的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-04-04