vue原理代码
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了vue原理代码,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2516字,纯文字阅读大概需要4分钟。
内容图文
<! 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><script src="./Kvue.js" type="text/javascript"></script></head><body><div id="app"> {{ message }}fsdafdsa <div><span><span><span> {{ message }}</span></span></span></div> {{mydata}} <div v-html="htmldata"></div><input v-model="modelData"/> {{modelData}} </div></body><script> let vm =new Kvue({ el:"#app", data:{ message:"测试数据1111", mydata:"some value", htmldata:"html数据", modelData:"双绑数据" } }) </script>
class Kvue{ constructor(option){ this.option=option; this._data=option.data; this.observer(); this.compile(); } //编译 compile(){ let ele=document.querySelector(this.option.el); let childNodes=ele.childNodes; this.compileNode(childNodes); } //对数据编译到元素上 compileNode(childNodes){ let textContent=""; let exp=null; childNodes.forEach((node,index)=>{ if(node.nodeType==3){ textContent= node.textContent; exp=/\{\{\s*(\S+)\s*\}\}/g; if(exp.test(textContent)){ // 初次渲染; let $1 = RegExp.$1; node.textContent=this._data[$1]; new Watcher(this,$1,newValue=>{ node.textContent=newValue; }); } } elseif(node.nodeType==1){ let attrs= node.attributes; [...attrs].forEach((attr,index)=>{ let name= attr.name; let value= attr.value; if(name=="v-model"){ node.addEventListener("input",ev=>{ this._data[value]=ev.target.value; }); new Watcher(this,value,newValue=>{ node.value=newValue; }); } }); if(node.childNodes.length>0){ this.compileNode(node.childNodes); } } }); } observer(){ Object.keys(this._data).forEach((key)=>{ let dep=new Dep(); let value= this.option.data[key]; Object.defineProperty(this._data,key,{ configurable: true, enumerable: true, get(){ if(Dep.target){ dep.addSub(Dep.target); } return value; }, set(newValue){ if(value!=newValue){ dep.notify(newValue); value=newValue; } } }); }) } } //发布订阅 Dep 类和 Watcherclass Dep{ constructor(){ this.subs=[]; } addSub(sub) {//订阅事件this.subs.push(sub); } notify(newValue) {//通知触发方法this.subs.forEach(v => { v.update(newValue); }) } } class Watcher { constructor(vm, exp, cb) { Dep.target = this; vm._data[exp]; this.cb = cb; Dep.target = null } update(newValue) { this.cb(newValue); } }
原文:https://www.cnblogs.com/supermanGuo/p/11448998.html
内容总结
以上是互联网集市为您收集整理的vue原理代码全部内容,希望文章能够帮你解决vue原理代码所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。