对属性值直接监听

对属性进行直接监听,通过创建dep=new Set,Set内可以add添加对象类型,并确保dep为唯一的不重复对象。

示例图:

image.png

代码:

  1. let price = 10,
  2. quantity = 4,
  3. total = 0;
  4. let dep = new Set();
  5. const effect = () => {
  6. total = price * quantity;
  7. };
  8. const track = () => {
  9. dep.add(effect);
  10. };
  11. const trigger = () => {
  12. if (dep) {
  13. dep.forEach(effect => effect());
  14. }
  15. };
  16. track();
  17. trigger();
  18. console.log('总价格total: ' + total);
  19. quantity = 9;
  20. trigger();
  21. console.log('总价格total: ' + total);
  22. price = 13;
  23. trigger();
  24. console.log('总价格total: ' + total);