- 通过Object.defineProperty()来进行数据劫持
demo.html
<body>
<div id="app">
{{message}}
</div>
<script>
var vm = new NanLan({
el: "#app",
data: {
message: 'hello vue',
age: "29",
hobby: "skating",
occupation: "programmer"
},
template: "<div>{{message}}</div>"
})
vm.message = 'hello xiaojuxiaoju';
console.log(vm.message);
</script>
</body>
demo.js
(function (root, factory) {
root.NanLan = factory()
})(this, function () {
function NanLan(options) {
this.$options = options || {};
var data = this._data = options.data; // 实例里面的data的所有属性
var _this = this;
// 代理
Object.keys(data).forEach(function (key) {
_this._proxy(key);
})
}
NanLan.prototype._proxy = function (key) {
Object.defineProperty(this, key, {
get: function () {
return this._data[key]; // 这里输出的是 hello xiaojuxiaoju
},
set: function (newValue) {
this._data[key] = newValue; // 将NanLan实例的值赋值给data里面与之对应的值
}
});
}
return NanLan;
})