[Vuejs]-How to do final state injection with Vue SRR with V8Js

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

Leave a comment