Vue.js与 ASP.NET Core 服务端渲染功能整合

2020-06-16 05:44:58易采站长站整理

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

总结

以上所述是小编给大家介绍的Vue.js与 ASP.NET Core 服务端渲染功能整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对软件开发网网站的支持!