The 2020-06-28 update
The method below is suitable for nuxT version 2.12. After version 2.12, there is a very simple way to deal with it. Instead of using asyncData hook, use fetch, a new life cycle hook, so that the code will not be triggered repeatedly.
During the nuxT project, the problem of page caching has always been a headache. I have been googling this problem for a long time, but I have not received any results. It is almost rude to tell you to use keep-alive, regardless of the related pits.
This article will share my tips on using Keep-Alive in NUxT and hopefully help you handle page caching more elegantly.
Layouts add keep alive
- First, establish the NUXT project
- in
./layouts/default.vue
Add the keep alive<template> <div> <nuxt keep-alive /> </div> </template> Copy the code
Processing asyncData
Because the keep-alive asyncData will still be triggered when the route is switched, we do a simple process to avoid this problem
// ./pages/index.vue
export default {
async asyncData({ app, store, error }) {
if(! process.server)return
const params = {
pageNum: 1
}
const { data } = await app.$getPostList(params)
return { postList: data.result, pageNum: 2 }
},
data() {
return {
pageNum: 1.postList: []
}
},
mounted() {
if (this.$store.state.is_browser_first) {
this.$store.commit('saveBrowserFirst'.false)}else {
const params = {
pageNum: this.pageNum
}
const { data } = await app.$getPostList(params)
this.postList = data.result
}
}
}
Copy the code
Explain the points you need to pay attention to in this paragraph
- asyncData
if (! process.server) return
If the non-server environment is directly retuen. willasyncDataControlling triggering only in the server environment saves us a lot of trouble.
- data
- We need to define the property again in data because if we do not define it, if we go to page B in browser environment page A, page B will report that the property does not exist because asyncData is not triggered.
- mounted
if (this.$store.state.is_browser_first){}
.is_browser_first
Is what I defined in vuex(./store/index.js). The default value istrue
, the main purpose is to record whether it is the first time to enter the browser, if yesis_browser_first
Set tofalse
, that is,saveBrowserFirst
Methods.
vuex
// ./store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = (a)= >
new Vuex.Store({
state: {
is_browser_first: true
},
mutations: {
saveBrowserFirst(state, type) {
state.is_browser_first = type
}
}
})
export default store
Copy the code
Existing problems
- error page
- When we go through
error({ statusCode: 404 })
Method If an error page is displayed and a route is returned, the error page is displayed. So what I’m going to do is I’m not going to route back, I’m going to passlocation
Methods.
- When we go through
If you have a better solution, please feel free to communicate with me. I hope this article can help the coder who has a headache about this matter.