Detailed vue source code tutorials and vue source code tutorials

Source: Internet
Author: User

Detailed vue source code tutorials and vue source code tutorials

Build Environment

Github address of the project

The project involves a json-server simulated get request and uses vue-router;

Vue lifecycle and vue-router Hook Function

Lifecycle

Version 1.0

1. What lifecycle interfaces?

initCreatedbeforeCompileCompiledReadyAttatchedDetachedbeforeDestorydestoryed

2. execution sequence

1. Do not have keep-alive

Go:

Init-> create-> beforeCompile-> complied-> attatched-> ready

Removal:

BeforeDestory-> detached-> destoryed;

2. With keep-alive

First time

Go:

Init-> create-> beforeCompile-> complied-> attatched-> ready

Removal:

Detached;

After each

Go:

Attatched

Removal:

Detached

Hook Function

3. What are hook functions?

Data
Activete
Deactivate
Canactivate
Candeactivate

4. execution sequence

Go:

Canactivate-> actiavte-> date

Removal:

Candeactivate-> deactiavte

Both appear together

5. For A sub-component B in component A, when the sub-component A is moved in and out, the execution sequence of the Life Cycle drinking hook function between components is as follows:

For example

A. vue

<Div>
<B> </B>
</Div>

Note: Nested child components are shown in the brackets below.

1. Do not have keep-alive:

Move in:

1. canActivate;
2. init;
3. create;
4. beforeCompile;
5. (nested child components: init, create, beforeCompile, compile );
6. compile;
7. activate;
8. data;
9. attached;
10. (sub-component attached );
11. (sub-component ready );
12. ready;

Removal:

13. canDeactivate;
14. deactivate;
15. beforeDestroy;
16. (child component beforeDestroy );
17. (sub-component destoryed );
18. detached;
19. (child component detached );
20. destoryed;

2. With keep-alive:

Move in:

1. canActivate;
2. activate;
3. data;
4. attached;
5. (sub-component attached );

Removal:

6. canDeactivate;
7. deactivate;
8. detached;
9. (child component detached );

6. execution sequence of the hook function activate and data

Asynchronous resolve rules involving hook functions:

1. If the hook returns a Promise, the time when the hook is resolve depends on the Promise and the time when it is resolve.

2. If the hook neither returns Promise nor has any parameters, the hook will be synchronized with resolve.

3. if the hook does not return Promise, but there is a parameter (transition), the hook will wait until transition. next (), transition. abort () or transition. one of redirect () is called before resolve.

4. In verification class hooks, such as canActivate, canDeactivate, and global beforeEach hooks, if the returned value is a Boolean value, the hooks are synchronized to resolve.

 
 

7. You can ensure that the interface has been updated, that is, the mounting process is complete.

Attached indicates that the task has been attached.

Bidirectional binding and rendering Mechanism

1. Data Monitoring and triggering (subscription and publishing of observer)

Observer under the src directory:

1. array. js

2. dep. js; (implement a publish and subscribe object)

3. index. js; (use the Object. defineProperty API and design a special getter/setter for this attribute, and then trigger a function in setter to achieve the listening effect );

The following is the source code of this part.

Object.defineProperty(obj, key, {enumerable: true,configurable: true,get: function reactiveGetter () {var value = getter ? getter.call(obj) : valif (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) : valif (newVal === value) {return}if (setter) {setter.call(obj, newVal)} else {val = newVal}childOb = observe(newVal)dep.notify()}})

The preceding listening and triggering code is simplified as follows:

function notidy(obj,key){console.log(key+" has changed");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 ctive. js under the src directory

You can see a series of parsed attributes in directive, and the instantiation of direve ve can be seen in utils/lifecycle. js.

The following code is in 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() can only be used inside twoWay' +'directives.')}}

Watch. js under the src directory:

The following code shows how to subscribe to a watcher object through the addDep method.

Watcher.prototype.addDep = function (dep) {var id = dep.idif (!this.newDepIds.has(id)) {this.newDepIds.add(id)this.newDeps.push(dep)if (!this.depIds.has(id)) {dep.addSub(this)}}}

2. As mentioned above, two-way binding is actually the internal rendering mechanism of VUE, which is summarized as follows:

1. The observer listens to data and provides the ability to subscribe to changes to a data item.

2. parse the template into a document fragment, and then parse the ve ctive to obtain the data items on which each directive depends and its update method. For example, after the v-text = "message" is parsed (the actual program logic is more rigorous and complex only for example): The dependent data item this. $ data. message, and the corresponding view update method node. textContent = this. $ data. message

3. watcher combines the above two parts, that is, the data in directive is subscribed to on the corresponding data observer, so that when the data changes, the observer will be triggered, this triggers the view update method corresponding to the dependency, and finally achieves the original association effect of the template.

3. How does vue improve v-for's error in rendering with the same data?

Array Rendering

The default id cached inside the rendering without the array of track-by is the value of the array, which means that if the same value exists in the array, the same fragement fragment is obtained through the id, finally, the operation of DOM through insertBefore is not effective because it is the same instance.

<div><ul id='test'><li id="child1">child1</li><li id="child">child2</li></ul></div><script>_element1=document.getElementById('child1');_element2=document.getElementById('child2');document.getElementById('test').insertBefore(_element1,_element2);</script>

The rendering result is child2 before child1.

The purpose of using track-by is to customize the internal id so that the items with the same value in the array will not be selected to the same instance, there are some differences between using track-by = '$ Index' and other unique id values, each of which has its own advantages.

Using $ index does not move the reversed data. Other IDs are used to move data in different order.

Rendering of Objects

An object generally uses a key as the id of an internal cache object. You can use track-by to customize this id to improve performance.

vm.model = {a: { id: 1, val: "model1"},b: { id: 2, val: "model2"},c: { id: 3, val: "model2"},}

List Update

vm.model = {d: { id: 1, val: "model1"},e: { id: 2, val: "model2"},f: { id: 3, val: "model2"}}

The above is a detailed tutorial on vue implementation from use to source code. I hope it will be helpful to you. If you have any questions, please leave a message and I will reply to you in a timely manner. Thank you very much for your support for the help House website!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.