欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 时评 > Vue2指令原理手写

Vue2指令原理手写

2025/2/24 13:08:06 来源:https://blog.csdn.net/mez_Blog/article/details/143407068  浏览:    关键词:Vue2指令原理手写

文件结构

index.js

/** @Author: RealRoad* @Date: 2024-10-31 17:13:50* @LastEditors: Do not edit* @LastEditTime: 2024-10-31 17:15:57* @Description: * @FilePath: \project_10_08\vite-project\src\testVue\index.js*/
import Vue from './Vue.js'
window.Vue=Vue

Vue.js

import Compile from './Compile.js'
import observe from './observe.js'
export default class Vue{constructor(options){//把参数options对象存为$optionsthis.$options = options ||{}//数据this._data=options.data || undefined;Observe(this._data)//数据要变为响应式的//模板编译new Compile(options.el,this)}
}

Compile.js

/** @Author: RealRoad* @Date: 2024-10-31 16:25:34* @LastEditors: Do not edit* @LastEditTime: 2024-10-31 16:28:44* @Description: * @FilePath: \project_10_08\vite-project\src\testVue\Compile.js*/
export default class Compile{constructor(el,vue){//vue实例this.$vue=vue;//挂载点this.$el=document.querySelector(el)if(this.$el){//调用函数,让节点变为fragment,类似与mustache中的tokens。//实际上用的是AST,这里就是轻量级的,fragmentlet $fragment= this.node2Fragment(this.$el);//编译this.compile($fragment);}
}node2Fragment(el){var fragment=document.createDocumentFragment();var child;//el为第一个子元素,循环添加到fragment中//让所有dom节点都添加到fragment中while(child=el.firstChild){fragment.appendChild(child);}return fragment}compile(el){//获取所有子节点var childNodes=el.childNodes;var self=this//遍历所有子节点for(let i=0,len=childNodes.length;i<len;i++){let node=childNodes[i];//判断是否是元素节点if(node.nodeType===1){self.compileElement(node);}else if(node.nodeType===3){self.compileText(node);}}}compileElement(node){//获取所有属性节点var attributes=node.attributes;//类数组变为数组[].slice.call(attributes).forEach(attr=>{if(attr.name==="v-model"){//获取属性值var value=attr.value;node.addEventListener("input",()=>{this.$vue[value]=node.value})}else if(attr.name==="v-text"){node.textContent=this.$vue[attr.value]}else if(attr.name==="v-html"){node.innerHTML=this.$vue[attr.value]}else if(attr.name==="v-bind"){node.setAttribute(attr.value,this.$vue[attr.value])}else if(attr.name==="v-on"){node.addEventListener(attr.value,()=>{})}else if(attr.name==="v-show"){node.style.display=this.$vue[attr.value]===true?"":"none"}else if(attr.name==="v-if"){node.style.display=this.$vue[attr.value]===true?"":"none"}})}compileText(){}
}

 

 

 

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词