码迷,mamicode.com
首页 > 其他好文 > 详细

解vue的数据binding原理(转)

时间:2018-08-28 20:12:20      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:name   mode   ide   pre   cti   oct   多个   nts   def   

<!DOCTYPE html>
<html>
<head>
<title>ideal</title>
<meta charset="utf-8">
</head>
<body>
<input class="test" type="text" name="asd" onkeyup="handleChange()" v-model="hey">
<input class="test" type="" name="" onkeyup="handleChange()" v-model="msg">
<script type="text/javascript">
//定义一个变量
var bindingMark = ‘data-element-binding‘

function Element(classa, initData) {
console.log("this zhi");
console.log(this);
var self = this,

el = self.el = document.getElementsByClassName(classa),//多个input改为class
bindings = {}
data = self.data = {}
for (var i = 0; i < el.length; i++) {
content = el[i].outerHTML.replace(/v-model=\"(.*)\"/g, markToken);

//设置默认值
el[i].outerHTML = content
}
for (var variable in bindings) {
bind(variable);
}
if (initData) {
for (var variable in initData) {
data[variable] = initData[variable]
}
}


function markToken(match, variable) {
bindings[variable] = {}
return bindingMark + ‘="‘ + variable + ‘"‘ //内填一个span变为只改它的元素
}

function bind(variable) {

bindings[variable].els = document.querySelectorAll(‘[‘ + bindingMark + ‘="‘ + variable + ‘"]‘)//document获取binding元素
;
Object.defineProperty(data, variable, {
set: function (newVal) {
[].forEach.call(bindings[variable].els, function (e) {
bindings[variable].value = e.value = newVal //=>textContent改为input的value
})
},
get: function () {
return bindings[variable].value
}
})
}
}

var app = new Element(‘test‘, {
msg: ‘hello‘,
hey: ‘aaa‘
})

function handleChange(e) { //增加v=>m的绑定


e = e || window.event
var key = e.target.outerHTML.match(/data-element-binding=\"(.*)\"/)[1];
console.log("outerHTML")
console.log(e.target.outerHTML);
console.log("key: " + key);
data[key] = e.target.value
console.log(data.hey, data.msg);
}
</script>
</body>
</html>




 

 

https://www.cnblogs.com/dh-dh/p/5606596.html

解vue的数据binding原理(转)

标签:name   mode   ide   pre   cti   oct   多个   nts   def   

原文地址:https://www.cnblogs.com/geekjsp/p/9550172.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!