0

The Vue SSR guide is mainly written for running a nodejs server and just touches on using V8Js in the final chapter.

It does have a section on final state injection but this doesn't work in the context of V8Js.

How can we pass the Vuex state from server to client side when using V8Js?

Felix Eve
  • 3,811
  • 3
  • 40
  • 50

1 Answers1

0

First in entry-server.js we need to print not just the app, but also the Vuex state.

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)
    })

And then in entry-client.js we need to populate the Vuex store with that data:

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')
})
Felix Eve
  • 3,811
  • 3
  • 40
  • 50