【问题标题】:Cannont mount twice the same Vue 3 component无法安装两次相同的 Vue 3 组件
【发布时间】:2022-01-16 10:05:08
【问题描述】:

我在帧加载期间安装了一个 Vue 3 组件作为加载动画:

createApp(App).mount(e);

加载框架时,框架内容会在 html 中删除组件(但我猜不是 Vue)。此行为由 Vue 的外部系统管理。

当我尝试使用相同的命令重新加载组件时,该组件不显示。

如果我只重新挂载该组件,我会在控制台中出现以下警告并且该组件不会显示:

"[Vue warn]: App has already been mounted.
If you want to remount the same app, move your app creation logic into a factory function and create fresh app instances for each mount - e.g. `const createMyApp = () => createApp(App)`".

我还找到了一种复制问题的方法:

const app = createApp(App)
app.mount(el);
el.innerHtml = '';
app.mount(el);

我也尝试卸载组件,但没有成功:

const app = createApp(App);
app.mount(el);
app.unmount();
app.mount(el);

那么在外部擦除同一个 vue 组件时,再次显示它的正确方法是什么?

【问题讨论】:

    标签: vuejs3 mount


    【解决方案1】:

    更好的选择是使用Vue custom elements

    首先,创建一个带有 ce.vue 扩展名的经典 SFC:

    //test.ce.vue
    <template>
        <div class="text-primary">Test</div>
    </template>
    
    <script>
    export default {
        name: 'test',
    };
    </script>
    
    <style>
        .text-primary {
            color: red;
        }
    
    </style>
    

    然后在主脚本中:

    //app.js
    import Test from 'test.ce.vue';
    const testElement = defineCustomElement(Test);
    customElements.define('test-element', testElement);
    
    document.body.appendChild(document.createElement('test-element'));
    

    一旦在文档中检测到组件就会被渲染:

    <test-component>
        #shadow-root (open)
            <style>
                .text-primary {
                    color: red;
                }
            </style>
            <div class="text-primary">Test</div>
    </test-component>
    

    【讨论】:

      【解决方案2】:

      要挂载/卸载2个Vue实例,需要使用render方法。

      因此,例如下面的示例,此解决方案有效:

      var app = createApp({ render: () => h(App) })
      app.mount(el);
      el.innerHtml = '';
      app = createApp({ render: () => h(App) })
      app.mount(el);
      

      别忘了导入 h() 函数:

      import { createApp, h } from 'vue';
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-08-05
        • 1970-01-01
        • 1970-01-01
        • 2019-05-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-05
        相关资源
        最近更新 更多