Exploring VueJS server-side rendering and troubleshooting some issues. Using the latest VueJS Hackernews 2.0 as a starting point for this project.
Currently facing an obstacle:
The server fetches data using the preFetch
method. All seems well.
When a user navigates to this component, the same function is called within the beforeRouteEnter
function. Everything looks good.
However, on the initial page load, the preFetchData
function is executed twice - once in preFetch
and once in beforeRouteEnter
.
This behavior is expected due to the way Vue Router operates. The server runs preFetch
, and when Vue renders on the client side, beforeRouteEnter
is triggered.
Yet, I don't want Vue to fetch the data twice during the first load since it's already in the store from the server-side rendering via preFetch
.
I can't check if the data is in the store because I need that component to always make the API call on beforeRouteEnter
, except for the initial render coming from the server.
Any suggestions on how to retrieve the data only once in this scenario?
<template>
<div class="test">
<h1>Test</h1>
<div v-for="item in items">
{{ item.title }}
</div>
</div>
</template>
<script>
import store from '../store'
function preFetchData (store) {
return store.dispatch('GET_ITEMS')
}
export default {
beforeRouteEnter (to, from, next) {
// Only execute this on the client side, not on the server
// On the server, we have preFetch
if (process.env.VUE_ENV === 'client') {
console.log('beforeRouterEnter, only on client')
preFetchData(store)
next()
} else {
// Server side, just pass it
next()
}
},
name: 'test',
computed: {
items () {
return this.$store.state.items
}
},
preFetch: preFetchData // Only on server
}
</script>
<style lang="scss">
.test {
background: #ccc;
padding: 40px;
div {
border-bottom: 1px red solid;
}
}
</style>
In the snippet above: the API call is made through store.dispatch('GET_ITEMS')