English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
환경 구축
프로젝트에서 json이 포함되었습니다-서버 모의 get 요청에서 vue 사용-router;
Vue 생명주기에 대해 Vue-router 힙스터 함수 설명
생명주기
1. 0 버전
1. 생명주기 인터페이스
init 생성 beforeCompile 구성 준비 Attatched Detached beforeDestory destoryed
2. 실행 순서
1. keep를 가지지 않습니다.-alive
이동:
init->create->beforeCompile->complied->attatched->ready
이동:
beforeDestory->detached->destoryed;
2. keep를 가지고 있습니다.-alive
처음에
이동:
init->create->beforeCompile->complied->attatched->ready
이동:
detached;
이후의 각 번째
이동:
attatched
이동:
detached
hook 함수
3. hook 함수는 무엇인가요
data
activete
deactivate
canactivate
candeactivate
4. 실행 순서
이동:
canactivate->actiavte->date
이동:
candeactivate->deactiavte
둘 다 나타납니다
5. 컴포넌트 A에 서브 컴포넌트 B가 있을 때, 컴포넌트 A가 이동과 이동을 수행할 때, 컴포넌트 간의 라이프사이클과 hook 함수의 실행 순서는 다음과 같습니다:
예를 들어
A.vue
<div>
<B></B>
);/ul>
비고: 다음 괄호 안에는 내포된 서브 컴포넌트가 있습니다.
1. keep를 가지지 않습니다.-alive:
이동:
1. canActivate;
2. init;
3. create;
4. beforeCompile;
5. (내포된 서브 컴포넌트: init, create, beforeCompile, compile);
6. compile;
7. activate;
8. data;
9. attached;
10. (서브 컴포넌트 attached);
11. (서브 컴포넌트 ready);
12. ready;
이동:
13. canDeactivate;
14. deactivate;
15. beforeDestroy;
16. (서브 컴포넌트 beforeDestroy);
17. (서브 컴포넌트 destoryed);
18. detached;
19. (서브 컴포넌트 detached);
20. destoryed;
2. keep를 가지고 있습니다.-alive:
이동:
1. canActivate;
2. activate;
3. data;
4. attached;
5. (서브 컴포넌트 attached);
이동:
6. canDeactivate;
7. deactivate;
8. detached;
9. (서브 컴포넌트 detached);
6. activate와 data의 실행 순서
钩子 함수 비동기 resolve 규칙을 포함합니다:
1.钩이 Promise를 반환하면, hook이 언제 resolve되는지는 해당 Promise가 언제 resolve되는지에 따릅니다.
2.钩이 Promise를 반환하지 않고, 매개변수도 없으면, 그 hook이 동기적으로 resolve됩니다.
3.钩이 Promise를 반환하지 않고, transition이라는 매개변수가 있으면, transition.next(), transition.abort() 또는 transition.redirect() 중 하나가 호출되어야 resolve됩니다.
4. 클래스의 검증 히스토리, 예를 들어 canActivate, canDeactivate 및 전역 beforeEach 히스토리에서, 반환 값이布尔值 (Boolean)이면 히스토리가 동기로 resolve됩니다。
7. 어떻게 확인할 수 있도록 할 수 있는지에 대해, 즉 마운트가 완료되었다고 할 수 있는 것입니다
생명주기 attached가 실행되면 이미 마운트되었다는 것을 의미합니다
양방향 바인딩 및 렌더링 메커니즘
1. 데이터의 감지와 트리거(구독 및 발행 observer)
src 디렉토리 아래 observer:
1. array.js
2. dep.js;(publish-subscribe 객체를 구현합니다)
3. index.js;(Object.defineProperty API를 사용하여 이�性质에 특별한 getter를 설계합니다)/setter를 호출하고, setter 내에서 함수를 트리거하여 감지 효과를 달성합니다);
이 부분의 원본 코드는 다음과 같습니다:
Object.defineProperty(obj, key, { enumerable: true, configurable: true, get: function reactiveGetter () { var value = getter ? getter.call(obj) : val if (Dep.target) { dep.depend() if (childOb) { childOb.dep.depend() } if (isArray(value)) { for (var e, i = 0, l = value.length; i < l; i++) { e = value[i] e && e.__ob__ && e.__ob__.dep.depend() } } } return value }, set: function reactiveSetter (newVal) { var value = getter ? getter.call(obj) : val if (newVal === value) { return } if (setter) { setter.call(obj, newVal) } else { val = newVal } childOb = observe(newVal) dep.notify() } })}}
위의 감지와 트리거 코드를 간소화한 것은 다음과 같습니다:
function notidy(obj,key){ console.log(key+"변경되었습니다"); console.log(key+" now is: "+obj[key]); } function ToData(key,val){ var ob=this; Object.defineProperty(ob,key,{ enumerable:true, configurable:true, get:function(){ return val; }, set:function(newval){ if(newval==val){ return; } val=newval; notidy(this,key); } })}} }
src目录下directive.js
在directive中可以看到一系列解析出来的属性,而directive的实例化可以在utils/lifecycle.js中看到。
下面这段代码在Directive.prototype._bind中
var watcher = this._watcher = new Watcher( this.vm, this.expression, this._update, // callback { filters: this.filters, twoWay: this.twoWay, deep: this.deep, preProcess: preProcess, postProcess: postProcess, scope: this._scope } ) // v-model with inital inline value need to sync back to // model instead of update to DOM on init. They would // set the afterBind hook to indicate that. if (this.afterBind) { this.afterBind() } else if (this.update) { this.update(watcher.value) } Directive.prototype.set = function (value) { /* istanbul ignore else */ if (this.twoWay) { this._withLock(function () { this._watcher.set(value) })}} } else if (process.env.NODE_ENV !== 'production') { warn( 'Directive.set()는 twoWay 내에서만 사용할 수 있습니다' + 'directives.' ) } }
src 디렉토리 아래 Watch.js:
아래의 코드에서 watcher 객체가 addDep 메서드를 통해 구독을 실현하는 것을 찾을 수 있습니다
Watcher.prototype.addDep = function (dep) { var id = dep.id if (!this.newDepIds.has(id)) { this.newDepIds.add(id) this.newDeps.push(dep) if (!this.depIds.has(id)) { dep.addSub(this) } } }
2. 이전에 언급한 양방향 바인딩에 대해 많이 말씀드렸지만, 이것도 실제로는 VUE의 내부 렌더링 메커니즘입니다. 요약하면 다음과 같습니다
1. data에 observer를 통해 감시하고, 특정 데이터 항목의 변경에 대한 구독 능력을 제공합니다
2. template를 document fragment로 해석한 후, 그 안의 directive를 해석하여 각 directive가 의존하는 데이터 항목 및 업데이트 메서드를 얻습니다. 예를 들어 v-text="message"가 해석된 후 (이곳은 단순한 예시이며, 실제 프로그램 로직은 더욱 엄격하고 복잡합니다): 의존 데이터 항목 this.$data.message 및 해당 뷰 업데이트 메서드 node.textContent = this.$data.message
3. 위 두 부분을 watcher를 통해 결합하면, 즉 directive에서 데이터 의존성 구독을 해당 데이터의 observer에 맞추면, 데이터가 변경될 때마다 observer가 trigge되고, 그로 인해 관련 의존성에 대한 뷰 업데이트 메서드가 trigge되어, 마지막으로 템플릿의 원래 연결 효과에 도달합니다.
3.vue는 v-같은 데이터로 렌더링하는 for문이 오류를 발생시키는 이유는 무엇인가요?
배열의 렌더링
track을 사용하지 않음-by의 배열 렌더링 내부 캐싱의 기본 id는 배열의 값 value입니다. 즉, 배열에 동일한 값이 존재하면 id를 통해 가져오는 것은 동일한 하나의 fragment 부분입니다. 마지막으로 insertBefore操作 DOM이 동일한 하나의 인스턴스이기 때문에生效하지 않습니다.
<div> <ul id='test'> <li id="child1</li>1);/<li id="child">child ">child2);/<li id="child">child );/li> );/ul> div> <script>1_element1=document.getElementById('child <script>2_element2=document.getElementById('child ');1document.getElementById('test').insertBefore(_element2,_element );/<
script>2렌더링 결과는 child1child 내에서
앞서-use track-use $index 또는 다른 유일한 구분 id 값에 대해 차이가 있으며, 각각의 장점이 있습니다.
use $index를 사용하여 반전된 데이터가 이동 작업 없이, 다른 id를 사용하여 순서가 다를 때에는 해당 이동 작업이 발생합니다.
객체의 렌더링
객체는 일반적으로 키를 사용하여 내부 캐시 객체의 id로 사용되며, track-by도 이 id를 사용하여 성능을 향상시킬 수 있습니다.
vm.model = { a: { id: 1, val: "model"1}, b: { id: 2, val: "model"2}, c: { id: 3, val: "model"2}, }
목록 업데이트
vm.model = { d: { id: 1, val: "model"1}, e: { id: 2, val: "model"2}, f: { id: 3, val: "model"2"} }
위 내용은 편집자가 제공한 vue에서 사용법부터 소스 코드 구현까지의 자세한 튜토리얼을 소개했습니다. 많은 도움이 되길 바랍니다. 모든 질문이나 의문이 있으면 댓글을 달아주세요. 편집자는 즉시 답변을 드리겠습니다. 또한,呐喊 튜토리얼 사이트에 대한 지지에 감사드립니다!
선언: 본 내용은 인터넷에서 수집된 내용으로, 원작자에게 소유권이 있습니다. 내용은 인터넷 사용자가 자발적으로 기여하고 업로드한 것이며, 이 사이트는 소유권을 가지지 않으며, 인공 편집되지 않았으며, 관련 법적 책임도 부담하지 않습니다.涉嫌著作권 내용이 발견되면, notice#w 이메일을 통해 알려주시기 바랍니다.3codebox.com에 (이메일 발송 시 #을 @으로 변경하시고) 신고를 하시고 관련 증거를 제공하시면, 해당 내용이 실제로 침해된 것으로 확인되면, 이 사이트는 즉시 해당 내용을 삭제합니다.