From d1e81474c007684e24d2686fdb664d2b6b0d5588 Mon Sep 17 00:00:00 2001 From: yutent Date: Mon, 4 Sep 2023 14:00:23 +0800 Subject: [PATCH] =?UTF-8?q?store=E6=94=AF=E6=8C=81=E6=B7=B1=E5=B1=82?= =?UTF-8?q?=E4=BB=A3=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package.json | 2 +- src/store.js | 33 +++++++++++++++++++++++---------- 2 files changed, 24 insertions(+), 11 deletions(-) diff --git a/package.json b/package.json index d26d208..63276e8 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "wkitd", - "version": "1.1.1", + "version": "1.1.2", "type": "module", "main": "dist/index.js", "files": [ diff --git a/src/store.js b/src/store.js index 3c4630e..1929c08 100644 --- a/src/store.js +++ b/src/store.js @@ -7,6 +7,28 @@ import { Component } from 'wkit' import { __STORE__ } from './constants.js' +function observe(obj) { + if (obj === null) { + return obj + } + + return new Proxy(obj, { + get(target, key, receiver) { + let value = Reflect.get(target, key, receiver) + // 当访问的值是对象时,需要对这个对象也进行代理 + if (typeof value === 'object') { + return observe(value) + } + return value + }, + set(target, key, value, receiver) { + Reflect.set(target, key, value, receiver) + window.wkitd.broadcast() + return true + } + }) +} + export function createStore(obj = {}) { let defined = false @@ -21,16 +43,7 @@ export function createStore(obj = {}) { 'Can not set readonly property $store of Component' ) } - window.wkitd.set( - __STORE__, - new Proxy(val, { - set(target, prop, value) { - target[prop] = value - window.wkitd.broadcast() - return true - } - }) - ) + window.wkitd.set(__STORE__, observe(val)) defined = true }, enumerable: false