H246802 / 30-days-challenge

30天每日打卡
4 stars 0 forks source link

day-27-自定义vue-computed #27

Open H246802 opened 5 years ago

H246802 commented 5 years ago

简单模拟 Vuecomputed 功能:

function Vue(options) {
  // your code
}
let app = new Vue({
  data: {
    firstName: 'Frank',
    lastName: 'Fang'
  },
  computed: {
    name() {
      return this.firstName + ' ' + this.lastName
    }
  }
})

console.log(app.name) // 'Frank Fang'
app.firstName = 'Jack'
console.log(app.name) // 'Jack Fang'
// 不要求实现 app.name 的赋值操作
H246802 commented 5 years ago

function Vue (options) {
    var Dep = null
    let {data, computed} = options
    this.data = data
    this.computed = computed

    var deps = [];
    for (let key in this.data) {
        Object.defineProperty(this, key, {
            get: function () {
                if (Dep) {
                    deps.push(Dep)
                }
                return this.data[key]
            },
            set: function (value) {
                this.data[key] = value
                deps.forEach(func => {
                    func()
                })
            }
        })
    }

    for (let funcName in this.computed) {
        this.computed[funcName] = this.computed[funcName].bind(this)
        var value
        Dep = function () {
            value = this.computed[funcName]
        }
        value = this.computed[funcName]
        Dep = null

        Object.defineProperty(this, funcName, {
            get: function () {
                return value.call(this)
            }
        })
    }
}

// 测试用例
var a = new Vue({
    data: {
        name: 'liyang'
    },
    computed: {
        sayHi() {
            return this.name + ', hi!'
        }
    }
})