美文网首页
vue中watch方法的实现

vue中watch方法的实现

作者: 李永州的FE | 来源:发表于2018-04-06 17:01 被阅读0次

虽然还很粗糙,比如制作的api很简陋,不过也总算是弄读懂了如何封装楼!!!!!

 var a = {
       name: 'h',
       age: '18'
   }
   function test() {
       this.arr = []
       this.watch = function (prop, fn) {
           this.arr.push(fn)
           var that  =this
           Object.defineProperty(a, prop, {
               get:function () {
                   console.log('取到了')
               },
               set:function (value) {
                   console.log('执行了')
                   that.arr[0]()
               }
           })
       }
   }
   Object.defineProperty(a, 'prop', {
       get:function () {
           console.log('取到了')
       },
       set:function (value) {
           this.arr[0]()
       }
   })
   var watcher = new test()
   watcher.watch('name', function () {
       console.log('被我监听到了')
   })
    a.name = 'hhh'

很多时候看别人的代码真的非常难读,好难读,还是自己些比较简单,前提是自己有思路

相关文章

网友评论

      本文标题:vue中watch方法的实现

      本文链接:https://www.haomeiwen.com/subject/nxzttftx.html