Vue.js SSR 數(shù)據(jù)預(yù)取和狀態(tài)

2021-01-07 15:54 更新

數(shù)據(jù)預(yù)取存儲容器 (Data Store)

在服務(wù)器端渲染(SSR)期間,我們本質(zhì)上是在渲染我們應(yīng)用程序的"快照",所以如果應(yīng)用程序依賴于一些異步數(shù)據(jù),那么在開始渲染過程之前,需要先預(yù)取和解析好這些數(shù)據(jù)。

另一個需要關(guān)注的問題是在客戶端,在掛載 (mount) 到客戶端應(yīng)用程序之前,需要獲取到與服務(wù)器端應(yīng)用程序完全相同的數(shù)據(jù) - 否則,客戶端應(yīng)用程序會因為使用與服務(wù)器端應(yīng)用程序不同的狀態(tài),然后導(dǎo)致混合失敗。

為了解決這個問題,獲取的數(shù)據(jù)需要位于視圖組件之外,即放置在專門的數(shù)據(jù)預(yù)取存儲容器(data store)或"狀態(tài)容器(state container))"中。首先,在服務(wù)器端,我們可以在渲染之前預(yù)取數(shù)據(jù),并將數(shù)據(jù)填充到 store 中。此外,我們將在 HTML 中序列化(serialize)和內(nèi)聯(lián)預(yù)置(inline)狀態(tài)。這樣,在掛載(mount)到客戶端應(yīng)用程序之前,可以直接從 store 獲取到內(nèi)聯(lián)預(yù)置(inline)狀態(tài)。

為此,我們將使用官方狀態(tài)管理庫 Vuex 。我們先創(chuàng)建一個 store.js 文件,里面會模擬一些根據(jù) id 獲取 item 的邏輯:

  1. // store.js
  2. import Vue from 'vue'
  3. import Vuex from 'vuex'
  4. Vue.use(Vuex)
  5. // 假定我們有一個可以返回 Promise 的
  6. // 通用 API(請忽略此 API 具體實現(xiàn)細節(jié))
  7. import { fetchItem } from './api'
  8. export function createStore () {
  9. return new Vuex.Store({
  10. state: {
  11. items: {}
  12. },
  13. actions: {
  14. fetchItem ({ commit }, id) {
  15. // `store.dispatch()` 會返回 Promise,
  16. // 以便我們能夠知道數(shù)據(jù)在何時更新
  17. return fetchItem(id).then(item => {
  18. commit('setItem', { id, item })
  19. })
  20. }
  21. },
  22. mutations: {
  23. setItem (state, { id, item }) {
  24. Vue.set(state.items, id, item)
  25. }
  26. }
  27. })
  28. }

然后修改 app.js

  1. // app.js
  2. import Vue from 'vue'
  3. import App from './App.vue'
  4. import { createRouter } from './router'
  5. import { createStore } from './store'
  6. import { sync } from 'vuex-router-sync'
  7. export function createApp () {
  8. // 創(chuàng)建 router 和 store 實例
  9. const router = createRouter()
  10. const store = createStore()
  11. // 同步路由狀態(tài)(route state)到 store
  12. sync(store, router)
  13. // 創(chuàng)建應(yīng)用程序?qū)嵗?,?router 和 store 注入
  14. const app = new Vue({
  15. router,
  16. store,
  17. render: h => h(App)
  18. })
  19. // 暴露 app, router 和 store。
  20. return { app, router, store }
  21. }

帶有邏輯配置的組件 (Logic Collocation with Components)

那么,我們在哪里放置「dispatch 數(shù)據(jù)預(yù)取 action」的代碼?

我們需要通過訪問路由,來決定獲取哪部分數(shù)據(jù) - 這也決定了哪些組件需要渲染。事實上,給定路由所需的數(shù)據(jù),也是在該路由上渲染組件時所需的數(shù)據(jù)。所以在路由組件中放置數(shù)據(jù)預(yù)取邏輯,是很自然的事情。

我們將在路由組件上暴露出一個自定義靜態(tài)函數(shù) asyncData。注意,由于此函數(shù)會在組件實例化之前調(diào)用,所以它無法訪問 this。需要將 store 和路由信息作為參數(shù)傳遞進去:

  1. <!-- Item.vue -->
  2. <template>
  3. <div>{{ item.title }}</div>
  4. </template>
  5. <script>
  6. export default {
  7. asyncData ({ store, route }) {
  8. // 觸發(fā) action 后,會返回 Promise
  9. return store.dispatch('fetchItem', route.params.id)
  10. },
  11. computed: {
  12. // 從 store 的 state 對象中的獲取 item。
  13. item () {
  14. return this.$store.state.items[this.$route.params.id]
  15. }
  16. }
  17. }
  18. </script>

服務(wù)器端數(shù)據(jù)預(yù)取 (Server Data Fetching)

entry-server.js 中,我們可以通過路由獲得與 router.getMatchedComponents() 相匹配的組件,如果組件暴露出 asyncData,我們就調(diào)用這個方法。然后我們需要將解析完成的狀態(tài),附加到渲染上下文(render context)中。

  1. // entry-server.js
  2. import { createApp } from './app'
  3. export default context => {
  4. return new Promise((resolve, reject) => {
  5. const { app, router, store } = createApp()
  6. router.push(context.url)
  7. router.onReady(() => {
  8. const matchedComponents = router.getMatchedComponents()
  9. if (!matchedComponents.length) {
  10. return reject({ code: 404 })
  11. }
  12. // 對所有匹配的路由組件調(diào)用 `asyncData()`
  13. Promise.all(matchedComponents.map(Component => {
  14. if (Component.asyncData) {
  15. return Component.asyncData({
  16. store,
  17. route: router.currentRoute
  18. })
  19. }
  20. })).then(() => {
  21. // 在所有預(yù)取鉤子(preFetch hook) resolve 后,
  22. // 我們的 store 現(xiàn)在已經(jīng)填充入渲染應(yīng)用程序所需的狀態(tài)。
  23. // 當(dāng)我們將狀態(tài)附加到上下文,
  24. // 并且 `template` 選項用于 renderer 時,
  25. // 狀態(tài)將自動序列化為 `window.__INITIAL_STATE__`,并注入 HTML。
  26. context.state = store.state
  27. resolve(app)
  28. }).catch(reject)
  29. }, reject)
  30. })
  31. }

當(dāng)使用 template 時,context.state 將作為 window.__INITIAL_STATE__ 狀態(tài),自動嵌入到最終的 HTML 中。而在客戶端,在掛載到應(yīng)用程序之前,store 就應(yīng)該獲取到狀態(tài):

  1. // entry-client.js
  2. const { app, router, store } = createApp()
  3. if (window.__INITIAL_STATE__) {
  4. store.replaceState(window.__INITIAL_STATE__)
  5. }

客戶端數(shù)據(jù)預(yù)取 (Client Data Fetching)

在客戶端,處理數(shù)據(jù)預(yù)取有兩種不同方式:

  1. 在路由導(dǎo)航之前解析數(shù)據(jù):

使用此策略,應(yīng)用程序會等待視圖所需數(shù)據(jù)全部解析之后,再傳入數(shù)據(jù)并處理當(dāng)前視圖。好處在于,可以直接在數(shù)據(jù)準(zhǔn)備就緒時,傳入視圖渲染完整內(nèi)容,但是如果數(shù)據(jù)預(yù)取需要很長時間,用戶在當(dāng)前視圖會感受到"明顯卡頓"。因此,如果使用此策略,建議提供一個數(shù)據(jù)加載指示器 (data loading indicator)。

我們可以通過檢查匹配的組件,并在全局路由鉤子函數(shù)中執(zhí)行 asyncData 函數(shù),來在客戶端實現(xiàn)此策略。注意,在初始路由準(zhǔn)備就緒之后,我們應(yīng)該注冊此鉤子,這樣我們就不必再次獲取服務(wù)器提取的數(shù)據(jù)。

  1. // entry-client.js
  2. // ...忽略無關(guān)代碼
  3. router.onReady(() => {
  4. // 添加路由鉤子函數(shù),用于處理 asyncData.
  5. // 在初始路由 resolve 后執(zhí)行,
  6. // 以便我們不會二次預(yù)取(double-fetch)已有的數(shù)據(jù)。
  7. // 使用 `router.beforeResolve()`,以便確保所有異步組件都 resolve。
  8. router.beforeResolve((to, from, next) => {
  9. const matched = router.getMatchedComponents(to)
  10. const prevMatched = router.getMatchedComponents(from)
  11. // 我們只關(guān)心非預(yù)渲染的組件
  12. // 所以我們對比它們,找出兩個匹配列表的差異組件
  13. let diffed = false
  14. const activated = matched.filter((c, i) => {
  15. return diffed || (diffed = (prevMatched[i] !== c))
  16. })
  17. if (!activated.length) {
  18. return next()
  19. }
  20. // 這里如果有加載指示器 (loading indicator),就觸發(fā)
  21. Promise.all(activated.map(c => {
  22. if (c.asyncData) {
  23. return c.asyncData({ store, route: to })
  24. }
  25. })).then(() => {
  26. // 停止加載指示器(loading indicator)
  27. next()
  28. }).catch(next)
  29. })
  30. app.$mount('#app')
  31. })

  1. 匹配要渲染的視圖后,再獲取數(shù)據(jù):

此策略將客戶端數(shù)據(jù)預(yù)取邏輯,放在視圖組件的 beforeMount 函數(shù)中。當(dāng)路由導(dǎo)航被觸發(fā)時,可以立即切換視圖,因此應(yīng)用程序具有更快的響應(yīng)速度。然而,傳入視圖在渲染時不會有完整的可用數(shù)據(jù)。因此,對于使用此策略的每個視圖組件,都需要具有條件加載狀態(tài)。

這可以通過純客戶端 (client-only) 的全局 mixin 來實現(xiàn):

  1. Vue.mixin({
  2. beforeMount () {
  3. const { asyncData } = this.$options
  4. if (asyncData) {
  5. // 將獲取數(shù)據(jù)操作分配給 promise
  6. // 以便在組件中,我們可以在數(shù)據(jù)準(zhǔn)備就緒后
  7. // 通過運行 `this.dataPromise.then(...)` 來執(zhí)行其他任務(wù)
  8. this.dataPromise = asyncData({
  9. store: this.$store,
  10. route: this.$route
  11. })
  12. }
  13. }
  14. })

這兩種策略是根本上不同的用戶體驗決策,應(yīng)該根據(jù)你創(chuàng)建的應(yīng)用程序的實際使用場景進行挑選。但是無論你選擇哪種策略,當(dāng)路由組件重用(同一路由,但是 params 或 query 已更改,例如,從 user/1user/2)時,也應(yīng)該調(diào)用 asyncData 函數(shù)。我們也可以通過純客戶端 (client-only) 的全局 mixin 來處理這個問題:

  1. Vue.mixin({
  2. beforeRouteUpdate (to, from, next) {
  3. const { asyncData } = this.$options
  4. if (asyncData) {
  5. asyncData({
  6. store: this.$store,
  7. route: to
  8. }).then(next).catch(next)
  9. } else {
  10. next()
  11. }
  12. }
  13. })

Store 代碼拆分 (Store Code Splitting)

在大型應(yīng)用程序中,我們的 Vuex store 可能會分為多個模塊。當(dāng)然,也可以將這些模塊代碼,分割到相應(yīng)的路由組件 chunk 中。假設(shè)我們有以下 store 模塊:

  1. // store/modules/foo.js
  2. export default {
  3. namespaced: true,
  4. // 重要信息:state 必須是一個函數(shù),
  5. // 因此可以創(chuàng)建多個實例化該模塊
  6. state: () => ({
  7. count: 0
  8. }),
  9. actions: {
  10. inc: ({ commit }) => commit('inc')
  11. },
  12. mutations: {
  13. inc: state => state.count++
  14. }
  15. }

我們可以在路由組件的 asyncData 鉤子函數(shù)中,使用 store.registerModule 惰性注冊(lazy-register)這個模塊:

  1. // 在路由組件內(nèi)
  2. <template>
  3. <div>{{ fooCount }}</div>
  4. </template>
  5. <script>
  6. // 在這里導(dǎo)入模塊,而不是在 `store/index.js` 中
  7. import fooStoreModule from '../store/modules/foo'
  8. export default {
  9. asyncData ({ store }) {
  10. store.registerModule('foo', fooStoreModule)
  11. return store.dispatch('foo/inc')
  12. },
  13. // 重要信息:當(dāng)多次訪問路由時,
  14. // 避免在客戶端重復(fù)注冊模塊。
  15. destroyed () {
  16. this.$store.unregisterModule('foo')
  17. },
  18. computed: {
  19. fooCount () {
  20. return this.$store.state.foo.count
  21. }
  22. }
  23. }
  24. </script>

由于模塊現(xiàn)在是路由組件的依賴,所以它將被 webpack 移動到路由組件的異步 chunk 中。

哦?看起來要寫很多代碼!這是因為,通用數(shù)據(jù)預(yù)取可能是服務(wù)器渲染應(yīng)用程序中最復(fù)雜的問題,我們正在為下一步開發(fā)做前期準(zhǔn)備。一旦設(shè)定好模板示例,創(chuàng)建單獨組件實際上會變得相當(dāng)輕松。

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號