Skip to content

Commit

Permalink
fix: 修改pinia的$subscribe回调方法无法在生产环境中使用
Browse files Browse the repository at this point in the history
  • Loading branch information
钟传德 committed Nov 18, 2024
1 parent 2f05287 commit 026bb72
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 11 deletions.
20 changes: 10 additions & 10 deletions core/init.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { PromiseMap, PromiseStatus, WatchConfig, WatchConfigCollection } from '../types'
import { generatePiniaKey } from '../utils'
import { generatePiniaKey, watchs } from '../utils'

class CustomHooks {
private watchConfigs: WatchConfigCollection = {}
Expand All @@ -11,7 +11,7 @@ class CustomHooks {
this.promiseMap[watch.key] = {
status: PromiseStatus.PENDING,
resolve,
onUpdate: watch.onUpdate,
onUpdate: watch.onUpdate
}
})
}
Expand Down Expand Up @@ -82,23 +82,22 @@ class CustomHooks {
init(watchObject: WatchConfigCollection): void {
this.watchConfigs = Object.assign({}, watchObject)
const watchItems = Object.values(this.watchConfigs)
watchItems.forEach(w => {
watchItems.forEach((w) => {
if (w.type === 'pinia') {
const piniaOriginalKey = w.key
const key = generatePiniaKey(w.key, w.store)
w.key = key
// @ts-ignore
w.store.$subscribe((store) => {
const { newValue } = store.events
watchs(w.store, piniaOriginalKey, (newValue: any) => {
this.updateWatchedValue(key, newValue)
})
}
const { key, onUpdate } = w;
const { key, onUpdate } = w
if (key) {
this.promiseCache[key] = this.createPendingPromise({ key, onUpdate })
} else {
console.error('init 方法无效的监听配置:缺少 key 属性')
}
});
})
}

getPromiseCache() {
Expand All @@ -117,10 +116,10 @@ class CustomHooks {
export const customHooks = new CustomHooks()

/**
*
*
* @param watchObject 监听的键
* @param target 传入的store
* @returns
* @returns
*/
export function init(watchObject: WatchConfigCollection) {
customHooks.init(watchObject)
Expand All @@ -135,3 +134,4 @@ export const createProxy = <T extends AnyObject>(target: T): T => customHooks.cr
export const proxyData = <T extends AnyObject>(target: T): T => {
return createProxy(target)
}

13 changes: 12 additions & 1 deletion utils/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { watch } from 'vue'
/**
* 生成唯一uuid
* @returns
* @returns
*/
export function generateUUIDv4() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
Expand All @@ -20,3 +21,13 @@ export function getSharedKey(watchKey: string[] | string, uuid: string): string
export function generatePiniaKey(key: string, store: any): string {
return `pinia-${store.$id}-${key}`
}

export function watchs(store: any, key: string, callback: Function) {
return watch(
() => store.$state[key],
(newVal) => {
callback(newVal)
},
{ immediate: false }
)
}

0 comments on commit 026bb72

Please sign in to comment.