The Vue component moves this. $el considerations

Source: Internet
Author: User

Like what

Mounted () {
Document.body.appendChild (this. $el);
Insertadjacentelement
InsertBefore
},

These lines of code cause the DOM element position to be inconsistent with the location expected by Vnode

Like what:

---------------------------------------

Parent component:

Div (id= ' P ')
H1, 1th one.
button (@click = "Add") new
P (v-for= "(item,index) in List",: key= "index")
| First {{Item}} elements
Ccc
---js section
Methods: {
Add () {
This.list.push (1);
}

}

---------------------------------------

Sub-component CCC:

Div
| I'm the document.body.append element.
---js section
Mounted () {
Document.body.appendChild (this. $el);
Insertadjacentelement
InsertBefore
}

---------------------------------------

Originally the CCC position in the Vnode its parent is the DIV element with ID p, and then because in mounted, the position of the $el is moved, causing its actual position to change, the parent node becomes the BODY element.

This results in the v-for p element in the parent component, rendering fails

Reason:

Clicking on the Parent component button will trigger the component's update, which will cause the new element to be insert into the DOM tree, which is in the Vue source code, Patch.js

function Insert (parent, elm, ref$$1) {
if (IsDef (parent)) {
if (IsDef (ref$$1)) {
if (Ref$$1.parentnode = = = Parent) {
Nodeops.insertbefore (Parent, Elm, ref$$1);
}
} else {
Nodeops.appendchild (parent, Elm);
}
}
}

When the new P element is inserted, the code is executed with three parameters: div (id= ' P '), p element itself, ref$$1 as CCC $el

Ref$$1.parentnode = = = Parent

Due to the change of the parent of CCC's $el, this line of judgment is invalid and rendering fails.

The Vue component moves this. $el considerations

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.