Skip to content

Instantly share code, notes, and snippets.

@felixheck
Last active March 29, 2020 11:54
Show Gist options
  • Save felixheck/6d748230270f07b5357d91660adf8133 to your computer and use it in GitHub Desktop.
Save felixheck/6d748230270f07b5357d91660adf8133 to your computer and use it in GitHub Desktop.
prefetch
// ./plugins/prefetch.js
export default ({ app, store }) => {
app.router.afterEach(() => {
Object.keys(store.state)
.filter((x) => !['app', 'menu'].includes(x))
.filter((x) => !store.state[x].fetched)
.forEach((x) => store.dispatch(`${x}/list`))
})
}
// ./nuxt.config.js
{
// ...
plugins: [{ src: '~/plugins/prefetch.js', mode: 'client' }]
// ...
}
// ./store/notes.js
export const state = () = ({
items: [],
fetched: false
})
export const mutations = {
LIST(state, data) {
state.items = data
state.fetched = true
}
}
export const actions = {
async list({ commit }) {
const data = await this.$axios.$get('/api/notes').catch(() => [])
commit('LIST', data)
return data
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment