有时候,我们需要将组件定义为全局组件,即组件在 HTML 根上,在任何地方都可以调用,比如 Alert 组件。
# react 版
import React from "react";
import ReactDOM from "react-dom";
import Alert from "./Alert";
const AlertWrapper = props => {
return new Promise(resolve => {
// 定义容器
let container = null;
if (document.getElementById("AlertContainer")) {
container = document.getElementById("AlertContainer");
} else {
container = document.createElement("div");
container.id = "AlertContainer";
document.body.appendChild(container);
}
// 将 Alert 渲染到容器
ReactDOM.render(
<Alert
open={props.open === undefined ? true : props.open}
title={props.title || "提示"}
msg={props.text}
onClose={() => {
resolve();
}}
/>,
container
);
});
};
export default AlertWrapper;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# vue 版(定义插件)
插件定义说明:https://cn.vuejs.org/v2/guide/plugins.html (opens new window)
const Toast = {};
Toast.install = function(Vue, options) {
Vue.prototype.$toast = tips => {
let ToastTpl = Vue.extend({
// 1、创建构造器,定义好提示信息的模板
template: '<div class="vue-toast">' + tips + "</div>"
});
let tpl = new ToastTpl().$mount().$el; // 2、创建实例,挂载到文档以后的地方
document.body.appendChild(tpl); // 3、把创建的实例添加到body中
setTimeout(function() {
// 4、延迟2.5秒后移除该提示
document.body.removeChild(tpl);
}, 2500);
};
};
Vue.use(Toast);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16