T
T
testopikachu2019-04-04 17:33:13
Vue.js
testopikachu, 2019-04-04 17:33:13

How to save component state in vue ssr?

Hello, can you please tell me if it is possible to save the states of components with vue server rendering?
That is, having received data on the server in such a component, I will lose it on the client and this.data will be empty.
The example is somewhat exaggerated, but still, how not to lose data?

//test.vue
<template>
  {{data}}
</template>

<script>
  export default {
    data() {
      return {
        data: ''
      }
    },

    serverPrefetch() {
      axios.get('/api/get/1')
        .then(result => {
          this.data = result.data
        })
    },
  }
</script>

The documentation tells how to save vuex state
//entry-server.js 
import { createApp } from './app'

export default context => {
  return new Promise((resolve, reject) => {
    const { app, router, store } = createApp()

    router.push(context.url)

    router.onReady(() => {
      context.rendered = () => {
        context.state = store.state //сохраняем состояние vuex
      }

      resolve(app)
    }, reject)
  })
}

//entry-client.js
import { createApp } from './app'

const { app, store, router } = createApp()

if (window.__INITIAL_STATE__) {
  store.replaceState(window.__INITIAL_STATE__) //загружем состояние vuex
}

router.onReady(function() {
  app.$mount('#app');
});

In general, I need this to solve the problem from this question - How to make a form using vuex?
I'm loading an object from vuex into a component for editing, after pressing the save button, I unload it back.
But with ssr it turns out that I have to call return this.$store.dispatch('fetch') first on the server and then on the client.
How to overcome it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Klein Maximus, 2019-04-09
@kleinmaximus

The Vue SSR documentation describes how to store state in the store. The mechanism used in this case implies the storage of data in the Store.
If hydration needs to be applied to components, then you need to either implement this functionality yourself, or use a hundred or so ready-made ones.
For example in UniversalVue or Nuxt .
PS: There will be no callback if you do it in , as described in the documentation . return this.$store.dispatch('fetch')asyncData

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question