Vue에서 Complie 데이터의 양방향 바인딩 원리에 대한 간략한 분석(자세한 코드 설명)
之前的文章《一文了解vue中watcher数据双向绑定原理(附代码)》中,给大家介绍了解了vue中complie数据双向绑定原理。下面本篇文章给大家了解vue中complie数据双向绑定原理,伙伴们过来看看吧。
vue
数据双向绑定原理,和简单的实现,本文将实现mvvm
的模板指令解析器
vue
数据双向绑定原理,和简单的实现,本文将实现mvvm
的模板指令解析器
上一步实现了简单数据绑定,最后实现解析器,来解析v-model,v-on:click
等指令,和{{}}
模板数据。解析器Compile
实现步骤:
解析模板指令,并替换模板数据,初始化视图
将模板指令对应的节点绑定对应的更新函数,初始化相应的订阅器
为了解析模板,首先需要获取到dom
元素,然后对含有dom
元素上含有指令的节点进行处理,因此这个环节需要对dom
操作比较频繁,所有可以先建一个fragment
片段,将需要解析的dom
节点存入fragment
片段里再进行处理:
function node2Fragment(el) { var fragment = document.createDocumentFragment(), child; // 将原生节点拷贝到fragment while ((child = el.firstChild)) { fragment.appendChild(child); } return fragment; }
接下来渲染'
{{}}'
模板
//Compile function Compile(el, vm) { this.$vm = vm; this.$el = this.isElementNode(el) ? el : document.querySelector(el); if (this.$el) { this.$fragment = this.node2Fragment(this.$el); this.init(); this.$el.appendChild(this.$fragment); } } Compile.prototype = { init: function () { this.compileElement(this.$fragment); }, node2Fragment: function (el) { //... }, //编译模板 compileElement: function (el) { var childNodes = el.childNodes, self = this; [].slice.call(childNodes).forEach(function (node) { var text = node.textContent; var reg = /{{(.*)}}/; //表达式文本 //按元素节点方式编译 if (self.isElementNode(node)) { self.compile(node); } else if (self.isTextNode(node) && reg.test(text)) { self.compileText(node, RegExp.$1); } //遍历编译子节点 if (node.childNodes && node.childNodes.length) { self.compileElement(node); } }); }, isElementNode: function (node) { return node.nodeType == 1; }, isTextNode: function (node) { return node.nodeType == 3; }, compileText: function (node, exp) { var self = this; var initText = this.$vm[exp]; this.updateText(node, initText); new Watcher(this.$vm, exp, function (value) { self.updateText(node, value); }); }, updateText: function (node, value) { node.textContent = typeof value == "undefined" ? "" : value; }, };
处理解析指令对相关指令进行函数绑定。
Compile.prototype = { ...... isDirective: function(attr) { return attr.indexOf('v-') == 0; }, isEventDirective: function(dir) { return dir.indexOf('on:') === 0; }, //处理v-指令 compile: function(node) { var nodeAttrs = node.attributes, self = this; [].slice.call(nodeAttrs).forEach(function(attr) { // 规定:指令以 v-xxx 命名 // 如 <span v-text="content"></span> 中指令为 v-text var attrName = attr.name; // v-text if (self.isDirective(attrName)) { var exp = attr.value; // content var dir = attrName.substring(2); // text if (self.isEventDirective(dir)) { // 事件指令, 如 v-on:click self.compileEvent(node, self.$vm, exp, dir); } else { // 普通指令如:v-model, v-html, 当前只处理v-model self.compileModel(node, self.$vm, exp, dir); } //处理完毕要干掉 v-on:, v-model 等元素属性 node.removeAttribute(attrName) } }); }, compileEvent: function(node, vm, exp, dir) { var eventType = dir.split(':')[1]; var cb = vm.$options.methods && vm.$options.methods[exp]; if (eventType && cb) { node.addEventListener(eventType, cb.bind(vm), false); } }, compileModel: function(node, vm, exp, dir) { var self = this; var val = this.$vm[exp]; this.updaterModel(node, val); new Watcher(this.$vm, exp, function(value) { self.updaterModel(node, value); }); node.addEventListener('input', function(e) { var newValue = e.target.value; if (val === newValue) { return; } self.$vm[exp] = newValue; val = newValue; }); }, updaterModel: function(node, value, oldValue) { node.value = typeof value == 'undefined' ? '' : value; }, }
最后再关联起来
function Vue(options) { ..... observe(this.data, this); this.$compile = new Compile(options.el || document.body, this) return this; }
来尝试下效果
<!--html--> <div id="app"> <h2 id="name">{{name}}</h2> <input v-model="name" /> <h1 id="name">{{name}}</h1> <button v-on:click="test">click here!</button> </div> <script> new Vue({ el: "#app", data: { name: "chuchur", age: 29, }, methods: { test() { this.name = "My name is chuchur"; }, }, }); </script>
OK. 基本完善了
推荐学习:vue.js教程
위 내용은 Vue에서 Complie 데이터의 양방향 바인딩 원리에 대한 간략한 분석(자세한 코드 설명)의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











vue.js에서 JS 파일을 참조하는 세 가지 방법이 있습니다. & lt; script & gt; 꼬리표;; mounted () 라이프 사이클 후크를 사용한 동적 가져 오기; Vuex State Management Library를 통해 수입.

vue.js의 시계 옵션을 사용하면 개발자가 특정 데이터의 변경 사항을들을 수 있습니다. 데이터가 변경되면 콜백 기능을 트리거하여 업데이트보기 또는 기타 작업을 수행합니다. 구성 옵션에는 즉시 콜백을 실행할지 여부와 DEEP를 지정하는 즉시 포함되며, 이는 객체 또는 어레이에 대한 변경 사항을 재귀 적으로 듣는 지 여부를 지정합니다.

vue.js에서 bootstrap 사용은 5 단계로 나뉩니다 : Bootstrap 설치. main.js.의 부트 스트랩 가져 오기 부트 스트랩 구성 요소를 템플릿에서 직접 사용하십시오. 선택 사항 : 사용자 정의 스타일. 선택 사항 : 플러그인을 사용하십시오.

HTML 템플릿의 버튼을 메소드에 바인딩하여 VUE 버튼에 함수를 추가 할 수 있습니다. 메소드를 정의하고 VUE 인스턴스에서 기능 로직을 작성하십시오.

CSS 애니메이션 또는 타사 라이브러리를 사용하여 VUE에서 Marquee/Text Scrolling Effects를 구현하십시오. 이 기사는 CSS 애니메이션 사용 방법을 소개합니다. & lt; div & gt; CSS 애니메이션을 정의하고 오버플로를 설정하십시오 : 숨겨진, 너비 및 애니메이션. 키 프레임을 정의하고 변환을 설정하십시오 : Translatex () 애니메이션의 시작과 끝에서. 지속 시간, 스크롤 속도 및 방향과 같은 애니메이션 속성을 조정하십시오.

vue.js에서 게으른 로딩을 사용하면 필요에 따라 부품 또는 리소스를 동적으로로드 할 수 있으므로 초기 페이지로드 시간을 줄이고 성능을 향상시킵니다. 특정 구현 방법에는 & lt; keep-alive & gt를 사용하는 것이 포함됩니다. & lt; 구성 요소는 & gt; 구성 요소. 게으른 하중은 FOUC (Splash Screen) 문제를 일으킬 수 있으며 불필요한 성능 오버 헤드를 피하기 위해 게으른 하중이 필요한 구성 요소에만 사용해야합니다.

vue.js는 이전 페이지로 돌아갈 수있는 네 가지 방법이 있습니다. $ router.go (-1) $ router.back () 사용 & lt; router-link to = & quot;/quot; Component Window.history.back () 및 메소드 선택은 장면에 따라 다릅니다.

Vue DevTools를 사용하여 브라우저 콘솔에서 vue 탭을 보면 VUE 버전을 쿼리 할 수 있습니다. npm을 사용하여 "npm list -g vue"명령을 실행하십시오. package.json 파일의 "종속성"객체에서 vue 항목을 찾으십시오. Vue Cli 프로젝트의 경우 "vue -version"명령을 실행하십시오. & lt; script & gt에서 버전 정보를 확인하십시오. vue 파일을 나타내는 html 파일의 태그.
