【问题标题】:Mount vue component - Vue 3挂载 vue 组件 - Vue 3
【发布时间】:2021-05-08 02:51:46
【问题描述】:

我想在 Vue 3 中这样做

new ComponentName({ 
  propsData: {
    title: 'hello world',
  }
}).$mount();

但我收到此错误:VueComponents_component_name__WEBPACK_IMPORTED_MODULE_1__.default is not a constructor

目前,我们正在使用上述方法通过append在我们的旧版应用程序中附加 VUE 组件

我想在 VUE 3 上做同样的事情,但我还没有找到方法

提前致谢

【问题讨论】:

  • 不能挂载组件,需要挂载应用,并将组件添加到应用中。见docs

标签: vue.js vuejs3


【解决方案1】:

我找到了答案的解决方案,在 vue 3(外部 vue 项目)中安装 vue 组件与 vue 2 不同,这是方法:

// mount.js

import { createVNode, render } from 'vue'

export const mount = (component, { props, children, element, app } = {}) => {
    let el = element

    let vNode = createVNode(component, props, children)
    if (app && app._context) vNode.appContext = app._context
    if (el) render(vNode, el)
    else if (typeof document !== 'undefined' ) render(vNode, el = document.createElement('div'))

    const destroy = () => {
        if (el) render(null, el)
        el = null
        vNode = null
    }

    return { vNode, destroy, el }
}
  • el:要附加的 DOM 元素
  • vNode:Vue 实例
  • destroy:销毁组件

这是将vue 3组件直接附加到DOM的方式,可以如下使用:

// main.js

import { mount } from 'mount.js'

const { el, vNode, destroy } = mount(MyVueComponents,
      {
          props: {
            fields,
            labels,
            options
           },
           app: MyVueApp
      },
)

$element.html(el);

希望对您有所帮助,问候!

【讨论】:

  • 您好!是否有可能有更多的上下文?我在我的应用程序中加载的 mixin 方法中将这部分代码与 Vue 2 一起使用。我有同样的错误,但我不明白一些事情..你如何导入安装功能?并从哪里让实例应用程序传入 mount 的参数?提前致谢!
【解决方案2】:

为了让未来的访问者节省一些时间,我正在寻找相同的答案,并找到了一个插件,它与 Luis 在https://github.com/pearofducks/mount-vue-component 的答案中解释的完全一样

使其实现更简单。

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
【解决方案3】:

很容易创建一个新的 vue3 应用并直接挂载到 DOM,

    const appDef = {
        data() {
            return {title: 'hello world'};
        },
        template: '<div>title is: {{title}}</div>',
    }

    var el = document.createElement('div');//create container for the app

    const app = Vue.createApp(appDef);
    app.mount(el);//mount to DOM
    
    //el: DOM element to be appended
    console.log(el.innerHTML);//title is: hello world

【讨论】:

    猜你喜欢
    • 2021-05-25
    • 1970-01-01
    • 2023-04-08
    • 2018-01-21
    • 2017-03-31
    • 2019-06-03
    • 2020-03-07
    • 2018-10-30
    • 2017-08-29
    相关资源
    最近更新 更多