Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving Vue components around inside the dom?

I am moving Vue components up in the dom if I am on mobile since I want to use positioning absolute and want to make sure I am not within a relative container.

if (this.mobile) {
    this.$el.parentNode.removeChild(this.$el);
    document.getElementById('vue').appendChild(this.$el);
} else {
    // Place the element back at it's original location.
}

This code is placed with a debounced resize method so it also works on resizing of the window.

It works fine but when I start out on mobile and resize back to desktop I need to get the original dom location of where the component was first initialized.

This might be a Javascript only question but how can I get the original location of the exact dom position of this component so I can place it back again?

Edit

I am saving the initial parent element with:

this.parent = this.$el.parentElement;

This does not guarantee the right order in the parent element though when I append the element back to the parentElement again.

like image 461
Stephan-v Avatar asked Jul 18 '17 12:07

Stephan-v


People also ask

How do you wrap a component in Vue?

Place the component you wish to wrap into the template of the wrapper component, add v-bind="$attrs" v-on="$listeners" to that component tag, then add the inner component (and, optionally, inheritAttrs: false ) to the wrapper component's config object.

How do I switch between Vue components?

Each component can be linked by using props to pass the methods which will switch the components on triggering a certain event. Here is an example: HTML. CSS.

What is teleport component in Vue?

<teleport> is a Vue 3 component that helps render HTML elements from one component to a different part of the code. It allows you to move an object from one place to another.

What is teleport component?

<Teleport> is a built-in component that allows us to "teleport" a part of a component's template into a DOM node that exists outside the DOM hierarchy of that component.


1 Answers

You just want to save the original parentNode once and use it when you need it. Something like this ought to work. Depending on your setup, you might need to use insertBefore with Daniel Beck's hidden marker idea.

if (!this.originalParentNode) {
    this.originalParentNode = this.$el.parentNode;
}
if (this.mobile) {
    this.$el.parentNode.removeChild(this.$el);
    document.getElementById('vue').appendChild(this.$el);
} else {
    // Place the element back at its original location.
    this.originalParentNode.appendChild(this.$el);
}
like image 130
Roy J Avatar answered Nov 10 '22 00:11

Roy J