更強大的vue ssr實現(xiàn)預取數(shù)據(jù)的方式
我在前幾天的一篇文章中吹了兩個牛皮,截圖為證:

現(xiàn)在可以松口氣的說,這兩個牛皮都實現(xiàn)了,不過 vue-suspense 改名了,叫做 vue-async-manager 了,他能幫你管理 Vue 應用中的異步組件的加載和 API 的調用,提供了與 React Suspense 同名的 `<Suspense>` 組件,Github:
shuidi-fed/vue-async-manager github.com

第二個牛皮是在開發(fā) vue-async-manager 的過程中臨時產生的一個靈感,覺得相同的技巧可以用在 SSR 預取數(shù)據(jù)上,但是當時還沒有嘗試,只是有個想法而已,不過很幸運,我成功了,GitHub:
https://github.com/HcySunYang/vue-ssr-prefetcher github.com
vue-ssr-prefetcher 為 Vue 的 SSR 提供更直觀更強大的數(shù)據(jù)預取方式(壓縮后僅 1kb )。讓我們來看看這張對比圖:

接下來詳細介紹一下 vue-ssr-prefetcher:
Why?
在 Vue 的服務端渲染中做數(shù)據(jù)預取的方式大概可以總結為兩種,一種是以 nuxt/ream 為代表的 asyncData 方案,另一種是 Vue 原生提供的 serverPrefetch 組件選項。然而這兩種方案都有一些缺點:
nuxt/ream 的 asyncData :
- 不能訪問 this
- 只能用于路由組件(或 page 組件)
- 需要通過返回對象(或 promise)將數(shù)據(jù)暴露到渲染環(huán)境
Vue 原生提供的 serverPrefetch :
- 只運行于服務端,客戶端需要另外編寫數(shù)據(jù)獲取邏輯,并避免數(shù)據(jù)的重復獲取
- 只能預取 store 數(shù)據(jù),無法將數(shù)據(jù)暴露到組件級別的渲染環(huán)境并發(fā)送到客戶端
以上兩種方案還擁有一個共同的弊端: 不夠直觀 (不直觀,因為這與開發(fā) SPA 時編寫代碼的方式不同), vue-ssr-prefetcher 提供了一種更直觀的數(shù)據(jù)預取方案,換句話說你在預取數(shù)據(jù)的過程中看不出來任何 SSR 的痕跡,就想在編寫 SPA 應用一樣。
安裝
yarn add vue-ssr-prefetcher
Or use npm :
npm install vue-ssr-prefetcher --save
使用
vue-ssr-prefetcher 提供了兩個 vue 插件: serverPlugin 和 clientPlugin ,分別用于 server entry 和 client entry 。
在 server entry 中:
import Vue from 'vue'
import createApp from './createApp'
// 1. 引入 serverPlugin
import { serverPlugin } from 'vue-ssr-prefetcher'
// 2. 安裝插件
Vue.use(serverPlugin)
export default async context => {
const { app, router, store } = createApp()
router.push(context.url)
await routerReady(router)
// 3. 設置 context.rendered 為 serverPlugin.done
context.rendered = serverPlugin.done
// 4. app.$$selfStore 是 serverPlugin 插件注入的屬性
context.state = {
$$stroe: store ? store.state : undefined,
$$selfStore: app.$$selfStore
}
return app
}
function routerReady (router) {
return new Promise(resolve => {
router.onReady(resolve)
})
}
serverPlugin 會在根組件實例上注入 app.$$selfStore 屬性,存儲著組件級別的數(shù)據(jù),你只需要將他添加到 context.state 中即可。另外,你還需要將 context.rendered 設置為 serverPlugin.done 。
在 client entry 中:
import Vue from 'vue'
import createApp from './createApp'
// 1. 引入插件
import { clientPlugin } from 'vue-ssr-prefetcher'
// 2. 安裝插件
Vue.use(clientPlugin)
const { app, router, store } = createApp()
router.onReady(() => {
// 3. 從 window.__INITIAL_STATE__ 中解構出 $$selfStore
const { $$selfStore } = window.__INITIAL_STATE__
// 4. 將數(shù)據(jù)添加到跟組件實例
if ($$selfStore) app.$$selfStore = $$selfStore
app.$mount('#app')
// 5. 這個非常重要,它用于避免重復獲取數(shù)據(jù),并且一定要在 $mount() 函數(shù)之后
clientPlugin.$$resolved = true
})
來看看接下來如何做數(shù)據(jù)預取
按照上面的介紹配置完成后,你就可以在任何組件的 created 鉤子中發(fā)送請求預取數(shù)據(jù):
export default {
name: 'Example',
data() {
return { name: 'Hcy' }
},
async created() {
// this.$createFetcher() 函數(shù)是 clientPlugin 注入的
// 接收一個返回 promise 的函數(shù)作為參數(shù),例如用于請求 api 函數(shù)
const fetcher = this.$createFetcher(fetchName)
const res = await fetcher()
this.name = res.name
}
}
如上代碼所示,和過去唯一不同的就是你需要調用 this.$createFetcher 函數(shù)創(chuàng)建一個 fetcher ,你可能會覺得這不爽,然而實際上 this.$createFetcher 做的事情很簡單,下面是它的源碼:
Vue.prototype.$createFetcher = function(fetcher) {
const vm = this
return function(params: any) {
const p = fetcher(params)
vm.$$promises.push(p)
return p
}
}
僅僅是一個簡單的包裝,因此我們可以把通過 this.$createFetcher 函數(shù)創(chuàng)建得到的 fetcher 認為與原函數(shù)相同。
雖然看上去和開發(fā) SPA 應用時沒什么不同,但 vue-ssr-prefetcher 為你做了很多事情,讓我們來對比一下,還是剛才的那種圖:

當然了 vue-ssr-prefetcher 還為你做了:
- 避免重復獲取數(shù)據(jù)
- 當路由跳轉時應該能夠正常發(fā)送請求
而你幾乎什么都不需要做, 唯一需要做的就是使用 this.$createFetcher 函數(shù)創(chuàng)建 fetcher ,但這真的沒有任何黑科技。
為了配合 vuex 一塊使用,你只需要:
export default {
name: 'Example',
async created() {
const fetcher = this.$createFetcher(() => this.$store.dispatch('someAction'))
fetcher()
}
}
當然了使用 mapActions 將 action 映射為 methods 也是可以的。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
vue-next/runtime-core 源碼閱讀指南詳解
這篇文章主要介紹了vue-next/runtime-core 源碼閱讀指南詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-10-10
Vue+ElementUI table實現(xiàn)表格分頁
這篇文章主要為大家詳細介紹了Vue+ElementUI table實現(xiàn)表格分頁,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-12-12
淺析vue 函數(shù)配置項watch及函數(shù) $watch 源碼分享
這篇文章主要介紹了vue 函數(shù)配置項watch及函數(shù) $watch 源碼分享 ,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2018-11-11
詳解vue的數(shù)據(jù)劫持以及操作數(shù)組的坑
這篇文章主要介紹了vue的數(shù)據(jù)劫持以及操作數(shù)組的坑,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-04-04
vue.js利用defineProperty實現(xiàn)數(shù)據(jù)的雙向綁定
本篇文章主要介紹了用Node.js當作后臺、jQuery寫前臺AJAX代碼實現(xiàn)用戶登錄和注冊的功能的相關知識。具有很好的參考價值。下面跟著小編一起來看下吧2017-04-04

