前言:
demo效果:
1、刚进页面,渲染welcome.vue组件内容。2、向输入框中输入数据按回车,页面上追加text.vue组件内容,输入框中的数据也被传递给text.vue组件,并在页面上进行了展示。3、点击text.vue组件中的按钮触发自定义事件并传值给App.vue组件,在App.vue组件中进行打印输出!
图片展示:
刚进页面:
输入框输入内容按回车:
点击【结束】按钮触发自定义事件:
正文:
首先要先了解vue3中两个函数的作用:
h()函数,用于创建一个虚拟DOM
render()函数,用于输出虚拟DOM
welcom.vue组件:
<!-- welcom组件 -->
<template>
<div class="welcom">恭喜您有时间摸鱼学习!</div>
</template>
text.vue组件
<!-- text组件 -->
<template>
<div class="text">
<p>今天来学习h函数和render函数</p>
<span>输入框内容:{{ userName }}</span>
<button @click.stop="handleButton">结束</button>
</div>
</template>
<script setup lang="ts">
const props = defineProps<{
userName: string;
}>();
const emits = defineEmits(["ClickBtn"]);
function handleButton() {
emits("ClickBtn", `${props.userName}这是您给我的值还给您!`);
}
</script>
app.vue组件
<template>
<div class="message_wrap" ref="message_wrap">
<input v-model="input_value" @keyup.enter="changeInput" />
</div>
</template>
<script setup lang="ts">
import { h, render, onMounted, ref } from "vue";
//导入组件
import Welcom from "./components/welcome.vue";
import TextCom from "./components/text.vue";
let message_wrap_dom: any;
onMounted(() => {
message_wrap_dom = document.getElementsByClassName("message_wrap")[0];
appendChildrenToPage(message_wrap_dom, Welcom);
});
let message_wrap = ref();
function appendChildrenToPage(
dom: HTMLElement,
componentName: any,
value?: string
) {
let text = h(componentName, { userName: value, onClickBtn: getValeFromSon });
let new_message;
if (!message_wrap.value._vnode) {
new_message = h("div", { id: "message" }, [text]);
} else {
new_message = h("div", { id: "message" }, [
...message_wrap.value._vnode?.children,
text,
]);
}
render(new_message, dom);
}
let input_value = ref("");
function changeInput() {
appendChildrenToPage(message_wrap_dom, TextCom, input_value.value);
}
function getValeFromSon(val: any) {
console.log(val, "===触发自定义事件===");
}
</script>