【问题标题】:How to render Vue's main app to the body element?如何将Vue的主应用程序渲染到body元素?
【发布时间】:2017-08-03 18:23:30
【问题描述】:

我正在使用名为“pages”的付费主题的项目中构建管理页面。

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

【问题讨论】:

  • 您的主题是否使用来自body 的子选择器? (例如body &gt; div)。 Vue 不喜欢你挂载到 body 标签。

标签: javascript html css vue.js


【解决方案1】:

在 Vue 2.0 中,您无法将根实例挂载到 body 或 html 元素。您将收到[Vue warn]: Do not mount Vue to &lt;html&gt; or &lt;body&gt; - mount to normal elements instead. 错误消息。

提供的元素仅用作安装点。与 Vue 1.x 不同,挂载的元素在所有情况下都将替换为 Vue 生成的 DOM。因此不建议将根实例挂载到&lt;html&gt;&lt;body&gt;

https://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/

【讨论】:

    【解决方案2】:

    使用 Vue 3,您可以做到。

    let YourApp = {
      data() {
        return {
          message: 'Hello World!'
        }
      },
      template: `
          <nav>Nav</nav>
          <header>Header</header>
          <span> inspect to see it</span>
      `
    }
    
    // Browser Version - vue.global.js
    Vue.createApp(YourApp).mount('body')
    &lt;script src="https://cdn.jsdelivr.net/npm/vue@3.0.2/dist/vue.global.min.js"&gt;&lt;/script&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-10
      • 2023-03-23
      • 2020-01-23
      • 2021-04-05
      • 1970-01-01
      • 2021-01-30
      • 2018-04-19
      • 1970-01-01
      相关资源
      最近更新 更多