0

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

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

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

4

1 回答 1

0

首先,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>\n\r`)

            // 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')
})
于 2020-06-04T10:07:58.477 回答