Vue3:如何避免Vitejs在挂载应用时erase/replace全部DOM内容?

Vue3: how to avoid Vitejs to erase/replace all DOM content when mounting the app?

我来自 Vue 2,我曾经拥有我的 wordpress 标准 html 页面,并在其中使用了一些 Vue 组件。只需将容器传递给主应用 el 属性,然后我就可以在容器上使用我想要的组件,而无需删除或替换所有默认容器的内容。基本上,将 dom 元素传递给 el 属性,使该元素成为 Vue 应用程序及其所有内容(即使没有任何 Vue 组件)。

使用 Vue 3 和 createApp,似乎没有办法做到这一点,因为一旦我将应用程序安装到容器(比如#app),容器的所有内容就会被删除或替换为组件的模板(如果传递了一个组件)。即使是下面的,没有使用任何组件,也将清除所有#app 原始内容:

import { createApp } from 'vue'

createApp({

}).mount('#app');

如何避免?如何在免费 html 页面上使用一些备用组件?那么SFC怎么用呢?

技术上 Vue 总是替换元素的内容(Vue 2 替换元素本身,Vue 3 替换它的内部内容 - migration guide

IF 被挂载的 app/component 没有 template 选项或 render 函数,然后(并且只有那时)Vue 采用原始的DOM 元素的内容(在挂载之前)并尝试将其编译成渲染函数(这就是为什么在使用 in-DOM 模板时需要 Compiler + runtime build

这也意味着,如果您的页面主要由静态 HTML(来自 WordPress)和仅“少量”Vue 组成,则此解决方案非常无效,这也是 petit-vue exists (I recommend reading Comparison with standard Vue[=18 的原因=]

无论如何。我无法重现您的问题...

const app = Vue.createApp({
}).mount("#app")
<script src="https://unpkg.com/vue@3.2.9/dist/vue.global.js"></script>
<div id='app'>
  <div>
    <h2>Hello from HTML!</h2>
  </div>
</div>

那么有什么问题吗?

  1. 检查浏览器开发工具控制台是否有任何错误消息 - 如果编译步骤(从 DOM 检索到的模板)失败,Vue 确实不会呈现任何内容,感觉就像“Vue 在安装后删除所有内容”
  2. 提防DOM Template Parsing Caveats. Browsers tend to "fix" invalid HTML before Vue reads it from the DOM - can cause
  3. 请务必使用包含模板编译器的 Vue 发行版。如果不这样做也会导致错误并删除所有内容