描述
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)