watch.ts 518 B

12345678910111213141516171819202122232425
  1. function watch(
  2. this: {
  3. data: Record<string, string>
  4. } & any,
  5. key: string,
  6. callback: (val: any) => void,
  7. ) {
  8. console.log(this, '555')
  9. // 先执行一次watch
  10. callback.call(this, this.data[key])
  11. let that = this
  12. let tmpData = this.data[key]
  13. Object.defineProperty(this.data, key, {
  14. set: function (value) {
  15. tmpData = value
  16. callback.call(that, value)
  17. console.log('item change', value, key)
  18. },
  19. get: function () {
  20. return tmpData
  21. },
  22. })
  23. }
  24. export default watch