直接上代码吧,这个用法真的是效仿了.net的枚举。

vue的数据双向绑定就是用这个实现的。

代码:

  

html:
<input type="text" id="input1">
<input type="text" id="input2">
我每次比input1的值加1=>
<span id="span"></span> js:
var oInput1 = document.getElementById('input1');
var oInput2 = document.getElementById('input2');
var oSpan = document.getElementById('span');
var obj = {};
Object.defineProperties(obj, {
val1: {
configurable: true,
get: function() {
oInput1.value = 0;
oInput2.value = 0;
oSpan.innerHTML = 0;
return 0
},
set: function(newValue) {
oInput2.value = newValue;
oSpan.innerHTML = Number(newValue) ? Number(newValue) : 0
}
},
val2: {
configurable: true,
get: function() {
oInput1.value = 0;
oInput2.value = 0;
oSpan.innerHTML = 0;
return 0
},
set: function(newValue) {
oInput1.value = newValue;
oSpan.innerHTML = Number(newValue)+1;
}
}
})
oInput1.value = obj.val1;
oInput1.addEventListener('keyup', function() {
obj.val1 = oInput1.value;
}, false);
oInput2.addEventListener('keyup', function() {
obj.val2 = oInput2.value;
}, false);

  

监听变量值变化,数据双向绑定:

  

html:
<button onclick="plus()">  +  </button>
<p id="p">0</p>
js:
function plus() {
watchVal.val = ++watchVal.value;
var screen = document.getElementById('p');
var text='00';
text=watchVal.value;
screen.innerHTML = text;
console.log(watchVal.value)
}
var watchVal = {
value: 0,
get val() {
console.log('取值', this.value);
return this.value;
},
set val(vals) {
this.value = vals;
console.log('存过后的值', this.value);
}
}

  

【未完待续,后续我封装一个自己的插件哦~】

04-28 19:39