Cache and Preloading You can enable caching functionality by setting the cacheKey
. When caching is enabled, VueRequest caches the results of the current request. The next time the component is initialized, or another request with the same cacheKey
is initialized, if there is a cache, it will return the cached data first, and then initiate a new request in the background. This ensures that data is displayed to the user as quickly as possible, which is also a form of preloading.
< template>
< div>
< NButton type = " primary" @click = " handleShow" >
{{ show ? 'Destory' : 'Render' }} children
</ NButton>
< br />
< br />
< NSpace v-if = " show" vertical >
< NSpace align = " center" >
< h3>     Cached:</ h3>
< CacheComponent />
</ NSpace>
< NSpace align = " center" >
< h3> Not cached:</ h3>
< NonCacheComponent />
</ NSpace>
</ NSpace>
</ div>
</ template>
< script lang = " ts" >
import { NButton, NSpace, NSpin, NTime } from 'naive-ui' ;
import { defineComponent, h, ref } from 'vue' ;
import { useRequest } from 'vue-request' ;
function testService ( ) {
return new Promise < number> ( resolve => {
setTimeout ( ( ) => {
resolve ( new Date ( ) . getTime ( ) ) ;
} , 1000 ) ;
} ) ;
}
const generateComponent = ( cached = false ) =>
defineComponent ( {
setup ( ) {
const opts = cached ? { cacheKey : 'date' } : { } ;
const { data, loading } = useRequest ( testService, opts) ;
return ( ) => {
if ( data. value === undefined && loading. value) {
return h ( NSpin, { size : 'small' } ) ;
}
return h ( NTime, { time : data. value } ) ;
} ;
} ,
} ) ;
const CacheComponent = generateComponent ( true ) ;
const NonCacheComponent = generateComponent ( ) ;
export default defineComponent ( {
name : 'App' ,
components : {
NButton,
NSpace,
CacheComponent,
NonCacheComponent,
} ,
setup ( ) {
const show = ref ( true ) ;
const handleShow = ( ) => {
show. value = ! show. value;
} ;
return {
show,
handleShow,
} ;
} ,
} ) ;
</ script>
< style scoped lang = " scss" > </ style>
Cache time You can also set the cache expiration time. When the cache data exceeds the set cacheTime
(default is 600000 milliseconds, which is 10 minutes), VueRequest will automatically discard the cached data and re-cache new data the next time a request is made.
const { data } = useRequest ( getJobType, {
cacheKey: 'JobType' ,
cacheTime: 5 * 60 * 1000 ,
} ) ;
Stale time If you can ensure that the cached data will not be updated within a certain time, you can set a stale time staleTime
(default is 0, which means no staleness). When a stale time is set, VueRequest will consider the cached data to be fresh within that time window and will not initiate a new request. This can reduce the load on some interfaces that are updated regularly.
const { data } = useRequest ( getJobType, {
cacheKey: 'JobType' ,
staleTime: 60 * 60 * 1000 ,
} ) ;
Request sharing When two requests have the same cacheKey
, only one request will be initiated at a time. The later request will share the same request with the first request.
In the following example, the content of the two components is always synchronized, and only one request is initiated when both are triggered simultaneously.
You can open the console and click the "run" button for each component to see the console output.
< template>
< div>
< NSpace vertical >
< NSpace align = " center" >
< h3> ComponentA:</ h3>
< ComponentA />
</ NSpace>
< NSpace align = " center" >
< h3> ComponentB:</ h3>
< ComponentB />
</ NSpace>
</ NSpace>
</ div>
</ template>
< script lang = " ts" >
import { NButton, NSpace, NSpin, NTime } from 'naive-ui' ;
import { defineComponent, h } from 'vue' ;
import { useRequest } from 'vue-request' ;
function testService ( ) {
return new Promise < number> ( resolve => {
console. log ( '[vue-request] fetching data...' ) ;
setTimeout ( ( ) => {
resolve ( new Date ( ) . getTime ( ) ) ;
} , 2000 ) ;
} ) ;
}
const generateComponent = ( ) =>
defineComponent ( {
setup ( ) {
const { data, loading, run } = useRequest ( testService, {
cacheKey : 'cacheRequest' ,
} ) ;
return ( ) => {
return h ( NSpin, { size : 'small' , show : loading. value } , ( ) => [
h ( NTime, { time : data. value } ) ,
h ( NButton, { style : 'margin-left: 30px' , type : 'primary' , onClick : run } , ( ) => 'Run' ) ,
] ) ;
} ;
} ,
} ) ;
const ComponentA = generateComponent ( ) ;
const ComponentB = generateComponent ( ) ;
export default defineComponent ( {
name : 'App' ,
components : {
NSpace,
ComponentA,
ComponentB,
} ,
setup ( ) {
return { } ;
} ,
} ) ;
</ script>
< style scoped lang = " scss" > </ style>
Dynamic cacheKey In addition to passing a string as the cacheKey
, you can also pass a function. The params
are passed as the parameter to the function, which returns a string as the final cacheKey
. This function can be used to implement dynamic cacheKey
functionality.
TIP
The input parameter params
of the cacheKey
function is undefined
during initialization. Therefore,
When manual = false
: return a key generated from default parameters or an empty string. When manual = true
: return an empty string. See the following example for reference.
const { data } = useRequest ( getJobType, {
manual: true ,
cacheKey : params => {
if ( params && params[ 0 ] ) {
return ` JobType- ${ params[ 0 ] } ` ;
}
return '' ;
} ,
staleTime: 60 * 60 * 1000 ,
} ) ;
You can use the following example to experience the effect:
You can open the console, switch the radio options, and check the console output.
< template>
< div>
< NRadioGroup v-model: value= " type" @update: value= " handleRun" >
< NSpace>
< NRadio :key = " 0" :value = " 0" > Chinese Names </ NRadio>
< NRadio :key = " 1" :value = " 1" > English Names </ NRadio>
</ NSpace>
</ NRadioGroup>
< NSpin :show = " loading" >
< ul v-if = " data" >
< li v-for = " item in data" :key = " item" > {{ item }}</ li>
</ ul>
</ NSpin>
</ div>
</ template>
< script lang = " ts" >
import { NRadio, NRadioGroup, NSpace, NSpin } from 'naive-ui' ;
import { defineComponent, ref } from 'vue' ;
import { useRequest } from 'vue-request' ;
const cnameData = [ '华强' , '大鹏' , '猹' , '张三' , '马冬梅' ] ;
const nameData = [ 'HuaQiang' , 'Peng' , 'Cha' , 'ZhangSan' , 'MaDongMei' ] ;
function getLocalName ( type : number) : Promise< string[ ] > {
console. log ( ` [vue-request] fetching data..., type = ${ type} ` ) ;
return new Promise ( resolve => {
setTimeout ( ( ) => {
resolve ( type ? nameData : cnameData) ;
} , 1000 ) ;
} ) ;
}
export default defineComponent ( {
components : {
NRadioGroup,
NRadio,
NSpin,
NSpace,
} ,
setup ( ) {
const type = ref ( 0 ) ;
const { data, loading, run } = useRequest ( getLocalName, {
staleTime : 10 * 1000 ,
defaultParams : [ 0 ] ,
cacheKey : params => {
if ( params?. [ 0 ] !== undefined ) {
return ` CacheDynamic- ${ params[ 0 ] } ` ;
}
return 'CacheDynamic-0' ;
} ,
} ) ;
const handleRun = ( value : number) => {
run ( value) ;
} ;
return {
data,
loading,
type,
handleRun,
} ;
} ,
} ) ;
</ script>
< style scoped lang = " scss" > </ style>
Clearing cache VueRequest provides a clearCache
method that can clear specified cacheKey
or all cached data.
Destory children
Clear cache
< template>
< div>
< NButton style = " margin-right : 20px" type = " primary" @click = " handleShow" >
{{ show ? 'Destory' : 'Render' }} children
</ NButton>
< NButton type = " primary" @click = " handleClear" > Clear cache </ NButton>
< br />
< br />
< NSpace v-if = " show" vertical >
< NSpace align = " center" >
< h3>     Cached:</ h3>
< CacheComponent />
</ NSpace>
</ NSpace>
</ div>
</ template>
< script lang = " ts" >
import { NButton, NSpace, NSpin, NTime } from 'naive-ui' ;
import { defineComponent, h, ref } from 'vue' ;
import { clearCache, useRequest } from 'vue-request' ;
function testService ( ) {
return new Promise < number> ( resolve => {
setTimeout ( ( ) => {
resolve ( new Date ( ) . getTime ( ) ) ;
} , 1000 ) ;
} ) ;
}
const generateComponent = ( ) =>
defineComponent ( {
setup ( ) {
const { data, loading } = useRequest ( testService, {
cacheKey : 'ClearCacheKey' ,
} ) ;
return ( ) => {
if ( data. value === undefined && loading. value) {
return h ( NSpin, { size : 'small' } ) ;
}
return h ( NTime, { time : data. value } ) ;
} ;
} ,
} ) ;
const CacheComponent = generateComponent ( ) ;
export default defineComponent ( {
name : 'App' ,
components : {
NButton,
NSpace,
CacheComponent,
} ,
setup ( ) {
const show = ref ( true ) ;
const handleShow = ( ) => {
show. value = ! show. value;
} ;
const handleClear = ( ) => {
console. log ( 'clear cache' ) ;
clearCache ( 'ClearCacheKey' ) ;
} ;
return {
show,
handleShow,
handleClear,
} ;
} ,
} ) ;
</ script>
< style scoped lang = " scss" > </ style>
Custom cache By configuring setCache
and getCache
, you can customize data caching, such as storing data in localStorage
, sessionStorage
, etc.
setCache
and getCache
must be used together.In custom cache mode, cacheTime
and clearCache
will not work, please implement them yourself. < template>
< div>
< NButton type = " primary" @click = " handleShow" >
{{ show ? 'Destory' : 'Render' }} children
</ NButton>
< br />
< br />
< NSpace v-if = " show" vertical >
< NSpace align = " center" >
< h3>     Cached:</ h3>
< CacheComponent />
</ NSpace>
</ NSpace>
</ div>
</ template>
< script lang = " ts" >
import { NButton, NSpace, NSpin, NTime } from 'naive-ui' ;
import { defineComponent, h, ref } from 'vue' ;
import { useRequest } from 'vue-request' ;
function testService ( ) {
return new Promise < number> ( resolve => {
setTimeout ( ( ) => {
resolve ( new Date ( ) . getTime ( ) ) ;
} , 1000 ) ;
} ) ;
}
const generateComponent = ( ) =>
defineComponent ( {
setup ( ) {
const { data, loading } = useRequest ( testService, {
cacheKey : 'VueRequestCustomCacheKey' ,
setCache : ( cacheKey, data ) => {
localStorage. setItem ( cacheKey, JSON . stringify ( data) ) ;
} ,
getCache : cacheKey => {
return JSON . parse ( localStorage. getItem ( cacheKey) || '{}' ) ;
} ,
} ) ;
return ( ) => {
if ( data. value === undefined && loading. value) {
return h ( NSpin, { size : 'small' } ) ;
}
return h ( NTime, { time : data. value } ) ;
} ;
} ,
} ) ;
const CacheComponent = generateComponent ( ) ;
export default defineComponent ( {
name : 'App' ,
components : {
NButton,
NSpace,
CacheComponent,
} ,
setup ( ) {
const show = ref ( true ) ;
const handleShow = ( ) => {
show. value = ! show. value;
} ;
return {
show,
handleShow,
} ;
} ,
} ) ;
</ script>
< style scoped lang = " scss" > </ style>