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 remended 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 mon to use document
to access DOM in Vue js?
Something like this :
methods:{
appendToBody(){
let node = document.createElement("div");
document.getElementById("#body").appendChild(node);
}
}
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 remended 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 mon to use document
to access DOM in Vue js?
Something like this :
methods:{
appendToBody(){
let node = document.createElement("div");
document.getElementById("#body").appendChild(node);
}
}
Share
Improve this question
edited Mar 18, 2019 at 10:15
Dheeraj Kumar
4087 silver badges17 bronze badges
asked Mar 18, 2019 at 9:51
Aref HoseinikiaAref Hoseinikia
1172 silver badges11 bronze badges
5
- why not you are using ponent? – Niklesh Raut Commented Mar 18, 2019 at 9:58
- how can i append a div to body by using ponents? i think vue js can just control #app element not the body. – Aref Hoseinikia Commented Mar 18, 2019 at 10:02
- Possible duplicate of Dynamic DOM elements add/remove with Vue – stdob-- Commented Mar 18, 2019 at 10:03
- @stdob-- no it couldn't help me. There is no data that i want to add or remove elements based on that data. i just want add an element to body out side of vue js instance(i mean #application section) – Aref Hoseinikia Commented Mar 18, 2019 at 10:09
- Why you need this ? what is your use case ? – Niklesh Raut Commented Mar 18, 2019 at 10:18
2 Answers
Reset to default 7It 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, ponents. If you need to access an DOM element that is a child of the current ponent 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.
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.