I followed the vite guide for Vue SSR and was able to migrate my Vue compositional API app to SSR and it works fine.
The only open issue that data fetching is still done on the client. I’m using the onMounted() hooks to fetch the data and it’s coming from a rest api.
Right now components who need to load data look something like this:
<script setup lang="ts">
...
const loaded = ref(false);
const data = ref([]);
// Client side hook. Could also be onMounted()
onBeforeMount(async () => {
data.value = await api.getSomething();
loaded.value = true;
});
</script>
The problem with these hooks is, that it is executed on the client side and not on the server. So the page is not delivered fully rendered but has the same behavior like without SSR.
I can only think of a kind of server side hook.
Does anybody know how to load the data on the server BEFORE the page is sent to the client?
Update 1
As @Estus Flask indicated, there is a <suspense/>
component which allows “orchestrating async dependencies”, so right now I have following code:
<template>
<RouterView v-slot="{ Component }">
<template v-if="Component">
<suspense>
<!-- main content -->
<component :is="Component"></component>
<!-- loading state -->
<template #fallback>
<span>Loading...</span>
</template>
</suspense>
</template>
</RouterView>
...
</template>
A page component now run the code above (reduced example):
<template>
<ul>
<li v-for="item in activeItems">{{ item.title }}</li>
</ul>
</template>
<script setup lang="ts">
...
// The data is stored in a central vuex store.
import { useStore } from '../store';
const api = createClient();
const store = useStore();
// Top-level await to block page execution(??)
const res = await api.getItems();
res.data.forEach(item => store.commit('addItem', item));
const activeItems = computed(() => store.state.items.slice().filter(x => x.active));
...
</script>
This renders fine, the problem is that the page load is not blocked but the page is delivered and then later updated when the data has arrived from the await api.getItems()
. So the behavior is as if I had not used SSR at all.
How do I block the page load so that the page is blocked and fully rendered served to the client?
4
Some lifecycle hooks like beforeMount
and mounted
are client-side only and can deliberately be used for this purpose. While setup function is executed on both server and client side. The component should use suspense in order for asynchronous actions such as data fetch to be used in SSR. So it should be:
const data = ref();
data.value = await api.getSomething();
Or if data
is not reactive besides the initial fetch:
const data = await api.getSomething();
4