描述
vue2和vue3中手动挂载组件案例
实现
vue2写法
import Vue from 'vue'
import ExtendTest from './views/ExtendTest.vue'
const ExtendTestObj = Vue.extend(ExtendTest)
export default {
mounted() {
this.$nextTick(() => {
const ele = document.createElement('div')
const instance = new ExtendTestObj({
// 传递props
propsData: {}
})
// 将组件挂载到ele上
const vm = instance.$mount(ele)
// 将节点ele添加到页面上
document.getElementById('app').appendChild(vm.$el)
})
}
}
vue3写法
// 创建一个Vue应用程序实例,并将该组件作为el创建
// 第一个参数是根组件。第二个参数可选,它是要传递给根组件的 props
const app = createApp(MyComponent, {
title: 'Hello Vue 3',
content: 'This is a dynamic Vue 3 component!',
});
const container = document.getElementById('app-container');
const ele = document.createElement('div')
// 挂载Vue应用到指定节点ele
app.mount(ele);
// 将节点ele添加到container
container.appendChild(ele)

文章详细介绍了在Vue2和Vue3中如何手动挂载组件。在Vue2中,通过`Vue.extend`创建组件实例,然后使用`$mount`方法挂载到DOM元素上。而在Vue3中,使用`createApp`创建应用实例并指定挂载点,再调用`mount`方法进行挂载。
865

被折叠的 条评论
为什么被折叠?



