如何使用 Vue SRR 和 V8Js 进行最终状态注入



Vue SSR 指南主要是为运行 nodejs 服务器而编写的,在最后一章中只谈到了使用 V8Js。

它确实有一个关于最终状态注入的部分,但这在 V8Js 的上下文中不起作用。

使用 V8Js 时,我们如何将 Vuex 状态从服务器端传递到客户端?

首先entry-server.js我们不仅需要打印应用程序,还需要打印 Vuex 状态。

import { createApp } from './app'
new Promise((resolve, reject) => {
const { app, router, store } = createApp()
router.push(url)
// Wait until router has resolved possible async components and hooks.
router.onReady(() => {
const matchedComponents = router.getMatchedComponents()
// No matched routes, reject with 404.
if (matchedComponents.length === 0) {
return reject({ code: 404 })
}
resolve(app)
}, reject)
})
.then(app => {
renderVueComponentToString(app, (err, res) => {
// Only now the app has rendered and all components have had a chance to 
// populate the Vuex store can we set the initial state.
const initialState = JSON.stringify(app.$store.state)
print(`<script>window.__INITIAL_STATE__ = ${initialState}</script>nr`)
// Print the markup for the app.
print(res)
})
})
.catch((err) => {
print(err)
})

然后在entry-client.js我们需要用这些数据填充 Vuex 商店:

import { createApp } from './app'
const { app, router, store } = createApp()
if (window.__INITIAL_STATE__) {
// Initialize the store state with the data injected from the server.
store.replaceState(window.__INITIAL_STATE__)
}
router.onReady(() => {
app.$mount('#app')
})

相关内容

  • 没有找到相关文章

最新更新