<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="app">
<p x-text="msg"></p>
<div x-text="eve"></div>
<button @click="handle">按钮</button>
</div>
<script>
const xgx = new Xgx({
el: '#app',
data: {
msg: 'haha',
eve: '你好'
},
methods: {
handle() {
this.eve = '呵呵'
}
}
})
function Xgx(option) {
this.el = option.el;
this.tmp = document.querySelector(this.el);
for(let key in option.methods) {
this[key] = option.methods[key]
}
for (let key in option.data) {
Object.defineProperty(this, key, {
get() {
return option.data[key]
},
set(val) {
for(let i = 0; i < this.tmp.children.length; i++) {
if(key == this.tmp.children[i].getAttribute('x-text')) {
console.log(this.tmp.children[i]);
this.tmp.children[i].innerText = val;
}
}
option.data[key] = val;
}
})
}
for(let i = 0; i < this.tmp.children.length; i++) {
if(this.tmp.children[i].getAttribute('x-text')) {
const key = this.tmp.children[i].getAttribute('x-text')
this.tmp.children[i].innerText = this[key];
}
if(this.tmp.children[i].getAttribute('@click')) {
this.tmp.children[i].onclick = this.handle.bind(this);
}
}
}
//视图层变让数据变 事件=function(){让数据变}
//让数据变,视图层也会变 ---》数据变触发函数
const obj = {};
Object.defineProperty(obj, 'abc', {
//val就是修改abc属性时,传入的值
set(val) {
//数据变,触发函数
console.log(this['abc']);
console.log('你在修改我的值');
},
get() {
//给添加的属性赋予默认值
return 'ls'
}
})
console.log(obj);
//案列
var vm = new Vue({
el: '#app',
// 在vue实例创建的时候,遍历data这个对象,Object.defineProperty动态添加我们自定义的属性 created(){} mounted() {}
data: {
msg: 'ls',
obj: {
name: 'ls'
}
},
methods: {
hand() {
// this.obj.age = 20;
this.$set(this.obj, 'age', 20)
}
}
//如果你在methods方法里 给obj动态添加属性不会造成页面更新
});
</script>
</body>
</html>
V-model底层原理(important)
最新推荐文章于 2025-07-06 22:42:23 发布
