I want to do this in Vue 3
new ComponentName({
propsData: {
title: 'hello world',
}
}).$mount();
But I'm getting this error: VueComponents_component_name__WEBPACK_IMPORTED_MODULE_1__.default is not a constructor
Currently, we are using the above approach to append VUE components in our legacy app via append
I would like to do the same on VUE 3 but I haven't found the way to do it
Thanks in advance
I found the solution to my answer, mounting a vue component in vue 3 (Outside vue projects) is different than vue 2, this is the approach:
import { createVNode, render } from 'vue'
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 }
}
This is the way to mount vue 3 components to be appended directly to the DOM, and can be used as below:
// Init contact us component and mount to auto-compile and be able to append inside $element
const { el, vNode, destroy } = mount(MyVueComponents,
{
props: {
fields,
labels,
options
},
app: MyVueApp
},
)
$element.html(el);
Hope it Helps, regards!
Just for future visitors to save some time, I was searching for the same answer and found a plug-in that does exactly what Luis explained en his answer at https://github.com/pearofducks/mount-vue-component
Makes it a little simpler to implement.
It is easy to create a new vue3 app and mount to a DOM directly,
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.