我正在一个元素中构建一个管理页面,该元素使用名为“页面”的付费主题。
问题是在这些主题中,<nav>
和 <header>
必须是 <body>
的直系子代.
当我使用 Vue 引导应用程序时,我将其渲染为 <div>
用id
设置为 root
.然后嵌套 <nav>
和 <header>
在此容器内(即在 <div id="root">
下)。
我一直在上下搜索如何让 Vue 组件成为 body 的直接子组件。
如何做到这一点?
我得到了什么:
<body>
<div>
<nav></nav>
<header></header>
</div>
</body>
主题需要什么:
<body>
<nav></nav>
<header></header>
</body>
最佳答案
在 Vue 2.0 中,您无法将根实例挂载到 body 或 html 元素。你会得到 [Vue warn]: Do not mount Vue to <html> or <body> - mount to normal elements instead.
错误信息。
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
解决方法是在组件 mount()
上手动移动您的元素事件。
<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>
示例工作流程:
new Vue({
el: '#app',
data: {
msg: 'message'
},
components: {
'navbar': {
template: `<navbar>{{ msg }}</navbar>`,
props: ['msg'],
mounted() {
document.body.insertBefore(this.$el, document.body.firstChild)
}
}
}
})
关于javascript - 如何将 Vue 的主应用渲染到 body 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42768667/