javascript - 如何将 Vue 的主应用渲染到 body 元素?

标签 javascript html css vue.js

我正在一个元素中构建一个管理页面,该元素使用名为“页面”的付费主题。

问题是在这些主题中,<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)
      }
    }
  }
})

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

关于javascript - 如何将 Vue 的主应用渲染到 body 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42768667/

相关文章:

javascript - 如何使用 jquery 更新 p(段落标记)的值

javascript - Protractor/Js - 无法获得准确的表格行数和列数

javascript - iPad CSS 悬停问题

javascript - Cookie 总是为空?

javascript - Chrome 扩展 : Issue with SendMessage

javascript - HTML/JS 注入(inject)攻击最简单的检查是什么?

javascript - 使用 CSS 和 JS 使通知向右淡出/消失

javascript - 点击时响应式滑动

javascript - 构建和部署 typescript/node.js 应用程序的明智方法

Javascript 不会替换我的 <div> 文本