@@ -2,8 +2,7 @@ import { useStyleInject } from '../StyleContext';
22import type { KeyType } from '../Cache' ;
33import useHMR from './useHMR' ;
44import type { ComputedRef , Ref } from 'vue' ;
5- import { onBeforeUnmount , computed , watch } from 'vue' ;
6- import eagerComputed from '../../eagerComputed' ;
5+ import { onBeforeUnmount , computed , watch , watchEffect , shallowRef } from 'vue' ;
76
87export default function useClientCache < CacheType > (
98 prefix : string ,
@@ -13,7 +12,10 @@ export default function useClientCache<CacheType>(
1312) : ComputedRef < CacheType > {
1413 const styleContext = useStyleInject ( ) ;
1514 const fullPath = computed ( ( ) => [ prefix , ...keyPath . value ] ) ;
16- const fullPathStr = eagerComputed ( ( ) => fullPath . value . join ( '_' ) ) ;
15+ const fullPathStr = shallowRef ( '' ) ;
16+ watchEffect ( ( ) => {
17+ fullPathStr . value = fullPath . value . join ( '_' ) ;
18+ } ) ;
1719 const HMRUpdate = useHMR ( ) ;
1820 const clearCache = ( paths : typeof fullPath . value ) => {
1921 styleContext . cache . update ( paths , prevCache => {
@@ -28,36 +30,37 @@ export default function useClientCache<CacheType>(
2830 return [ times - 1 , cache ] ;
2931 } ) ;
3032 } ;
31- watch (
32- ( ) => fullPath . value . slice ( ) ,
33- ( _ , oldValue ) => {
34- clearCache ( oldValue ) ;
35- } ,
36- ) ;
37- // Create cache
38- watch (
39- fullPathStr ,
40- ( ) => {
41- styleContext . cache . update ( fullPath . value , prevCache => {
42- const [ times = 0 , cache ] = prevCache || [ ] ;
4333
44- // HMR should always ignore cache since developer may change it
45- let tmpCache = cache ;
46- if ( process . env . NODE_ENV !== 'production' && cache && HMRUpdate ) {
47- onCacheRemove ?.( tmpCache , HMRUpdate ) ;
48- tmpCache = null ;
49- }
34+ watch (
35+ [ fullPathStr , fullPath ] ,
36+ ( [ newStr ] , [ oldStr , oldPath ] ) => {
37+ if ( newStr !== oldStr ) {
38+ if ( oldPath ) clearCache ( oldPath ) ;
39+ // Create cache
40+ styleContext . cache . update ( fullPath . value , prevCache => {
41+ const [ times = 0 , cache ] = prevCache || [ ] ;
5042
51- const mergedCache = tmpCache || cacheFn ( ) ;
43+ // HMR should always ignore cache since developer may change it
44+ let tmpCache = cache ;
45+ if ( process . env . NODE_ENV !== 'production' && cache && HMRUpdate ) {
46+ onCacheRemove ?.( tmpCache , HMRUpdate ) ;
47+ tmpCache = null ;
48+ }
49+ // console.log('create');
50+ const mergedCache = tmpCache || cacheFn ( ) ;
5251
53- return [ times + 1 , mergedCache ] ;
54- } ) ;
52+ return [ times + 1 , mergedCache ] ;
53+ } ) ;
54+ }
5555 } ,
5656 { immediate : true } ,
5757 ) ;
58+
5859 onBeforeUnmount ( ( ) => {
5960 clearCache ( fullPath . value ) ;
6061 } ) ;
61- const val = computed ( ( ) => styleContext . cache . get ( fullPath . value ) ! [ 1 ] ) ;
62+ const val = computed ( ( ) => {
63+ return styleContext . cache . get ( fullPath . value ) ! [ 1 ] ;
64+ } ) ;
6265 return val ;
6366}
0 commit comments