跳到主要内容

框架

vue3 实现 Message

<template>
<div class="message" v-if="isShow">
<p>{{ message }}</p>
</div>
<button @click="close">关闭窗口</button>
</template>

<script setup>
import { getCurrentInstance, ref } from "vue";

const props = defineProps({
message: {
type: String,
required: true,
},
duration: {
type: Number,
default: 3,
},
});
const isShow = ref(false);
const open = () => {
isShow.value = true;
setTimeout(() => {
isShow.value = false;
}, props.duration * 1000);
};
const close = () => {
isShow.value = false;
};

// 把方法挂到instance的ctx上
const instance = getCurrentInstance();
instance.ctx.open = open;
instance.ctx.close = close;
</script>

调用函数将组件挂到页面上

import { createApp, h } from "vue";
import messageComp from "./message.vue";

export const message = (props) => {
// 创建容器
const container = document.createElement("div");
let tem;
// 生成虚拟dom并挂载
createApp({
render() {
// 只有h函数能拿到组件的ctx
tem = h(messageComp, props);
return tem;
},
});
// 挂载容器组件
document.body.appendChild(container);
return {
// 暴露手动关闭弹窗的函数, // 只有h函数能拿到组件的ctx!
close: () => tem.component.ctx.close(),
open: () => tem.component.ctx.open(),
};
};

使用 先把它挂到全局属性上

import { createApp } from "vue";
import "./style.css";
import App from "./App.vue";
import { message } from "./components/message1.js";
const app = createApp(App);
app.config.globalProperties.$message = message;
app.mount("#app");



<template>
<div>hello</div>
<button @click="open">开启弹窗</button>
</template>

<script setup>
import { getCurrentInstance } from "vue";
const {proxy} = getCurrentInstance()
const {close,open} = proxy.$message({
message:"hi",
duration:2
})

</script>

<style scoped>

</style>

React 实现 Count 组件

import React, { useState } from "react";

export function App() {
const [count, setCount] = useState(0);
const updateCount = (diff) => {
setCount((prev) => prev + diff);
};
return (
// data-只是用来标识一下
// 取data的两种方式
// onClick event->event.target.getAttribute('data-testid')
// useRef ref.current.getAttribute('data-testid')

<div>
<button
data-testid="decrement"
onClick={() => {
updateCount(-1);
}}
>
-
</button>
<button
data-testid="increment"
onClick={() => {
updateCount(1);
}}
>
+
</button>
<p>clicked: {count}</p>
</div>
);
}