Reputation: 117
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);
}
}
Upvotes: 4
Views: 5365
Reputation: 14181
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.
Upvotes: 7
Reputation: 2821
You can use DOM functions like document.getElementById
in Vue to find elements, but never use DOM functions to change the DOM. Always do modifications within Vue by changing variables and react to it in the template.
Upvotes: 1