H246802/30-days-challenge

day-27-自定义vue-computed

Opened this issue · 1 comments

简单模拟 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 的赋值操作
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!'
		}
	}
})