Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
175
rated 0 times [  179] [ 4]  / answers: 1 / hits: 16815  / 7 Years ago, mon, march 13, 2017, 12:00:00

I am building an admin page in a project that uses a paid-for theme called pages.



The issue is that in these themes, <nav> and <header> must be direct children of <body>.



When I use Vue to bootstrap the app, I am rendering it to a <div> with an id that's set to root. This then nests the <nav> and <header> within this container (i.e. under <div id=root>).



I have been searching high and low on how to get Vue components to become direct children of body.



How to do this?






What I am getting:



<body>
<div>
<nav></nav>
<header></header>
</div>
</body>


What the theme needs:



<body>
<nav></nav>
<header></header>
</body>

More From » html

 Answers
297

With Vue 2.0 you cannot mount root instance to the body or html element. You will be getting [Vue warn]: Do not mount Vue to <html> or <body> - mount to normal elements instead. error message.



The provided element merely serves as a mounting point. Unlike in Vue 1.x, the mounted element will be replaced with Vue-generated DOM in all cases. It is therefore not recommended to mount the root instance to <html> or <body>.



https://v2.vuejs.org/v2/api/#el


The way around is to manually move your element on component mount() event.


<div id="app">
<navbar :msg="msg"></navbar>

Lorem ipsum dolor sit amet, consectetur adipisicing elit.

<button @click="msg = 'tested'">Test 2-way binding</button>
</div>

Example workflow:


new Vue({
el: '#app',
data: {
msg: 'message'
},
components: {
'navbar': {
template: `<navbar>{{ msg }}</navbar>`,
props: ['msg'],
mounted() {
document.body.insertBefore(this.$el, document.body.firstChild)
}
}
}
})

https://jsfiddle.net/jedrzejchalubek/m9dnsjjr/2/


[#58565] Friday, March 10, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
grayson

Total Points: 36
Total Questions: 113
Total Answers: 95

Location: Tonga
Member since Fri, Aug 21, 2020
4 Years ago
grayson questions
;