前言:
此篇文章自己结合项目和文档自己理解的,作用于往后遇见此类开发需求时参考。
正文:
1、createApp() 创建一个应用程序实例
function createApp(rootComponent: Component, rootProps?: object): App
第一个参数是根组件。第二个可选参数是将要传递给根组件的属性。
2、app.mount() 在容器元素中挂载应用程序实例。
interface App {mount(rootContainer: Element | string): ComponentPublicInstance
}
参数可以是实际的DOM元素或CSS选择器(将使用第一个匹配的元素)。返回根组件实例。
如果组件定义了模板或渲染函数,它将替换容器内的任何现有DOM节点。否则,如果运行时编译器可用,容器的innerHTML将被用作模板。
对于每个应用实例,mount()只能被调用一次。
运用:
App组件:
页面效果:
在App.vue组件中使用 createApp()函数,通过appendChild 往页面上追加元素
app.vue组件
<template><div id="message"></div>
</template><script setup lang="ts">
import { createApp, onMounted } from "vue";
import Children from "./components/children.vue";
let message: HTMLElement | null;
onMounted(() => {message = document.getElementById("message");createRealDom();
});const createRealDom = () => {const fragment = document.createDocumentFragment() as any;const config = {props: {userName: "Lee_Yu_Fan",address: "北京",},//自定义事件名称前加 ononClickBtn: (value: string) => {console.log("Children组件触发的事件", value);},};const com = createApp(Children, config); //当调用createApp后就会生成一个应用上下文实例,该实例暴露了相关功能APIconst dialog = com.mount(fragment) as any; //其中就包含mount函数,该函数实现组件挂载message?.appendChild(dialog.$el); //dialog.$el
};
</script>
<style scoped>
#message {width: 100%;height: 100%;
}
</style>
children.vue组件
<template><div class="child"><p>我是子组件</p><hr /><p>应用实例传递过来的属性</p><p>{{ props.userName }}</p><p>{{ props.address }}</p><button @click.stop="handlerClick">点击</button></div>
</template>
<script setup lang="ts">
defineProps<{props: {userName: string;address: string;};
}>();
const emits = defineEmits(["ClickBtn"]);
function handlerClick() {// 组件自定义事件emits("ClickBtn", "发送数据到应用实例");
}
</script>
<style>
.child {width: 300px;height: 400px;background-color: pink;
}
</style>
页面效果+点击按钮触发自定义事件后在控制台打印结果:
注意:
1、 直接在页面上使用组件
在children组件中使用 getCurrentInstance(),打印父组件和根组件
结果是: (App.vue)
2、 使用 createApp()函数,通过appendChild 往页面上追加元素,在children组件中使用 getCurrentInstance(),打印父组件和根组件,结果是:
所以,使用 createApp()函数,通过appendChild 往页面上追加的元素,本质上是一个独立的应用程序实例,如果想要使用第三方插件,需要再次通过use()去挂载