Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it good to access DOM in vue js?

I want to know is it OK to access DOM in a Vue js application? For example, if I want to append an element (div) to body tag is this recommended to use document.getElementById in a Vue js method?

I have no data that can be used to make or remove elements based on data. I really just want to know is it common to use document to access DOM in Vue js?

Something like this :

methods:{
 appendToBody(){
   let node = document.createElement("div");
   document.getElementById("#body").appendChild(node);
 }
}
like image 349
Aref Hoseinikia Avatar asked Mar 04 '23 08:03

Aref Hoseinikia


1 Answers

It depends on what part of the DOM you are referring too.

If you want to change the subtree that is handled by Vue, you shouldn't do that. You should rely on reactive properties, conditional rendering, components. If you need to access an DOM element that is a child of the current component you can use refs.

If you need to change a part of the DOM which is outside of Vue's realm then by all means do it.

In your case is not clear what you want to achieve and is hard to give a clear answer.

like image 74
Radu Diță Avatar answered Mar 11 '23 13:03

Radu Diță