Skip to content

react 和 vue 全局组件的实现方式

有时候,我们需要将组件定义为全局组件,即组件在 HTML 根上,在任何地方都可以调用,比如 Alert 组件。

react 版

jsx
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;
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;

vue 版(定义插件)

插件定义说明:https://cn.vuejs.org/v2/guide/plugins.html

javascript
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);
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);

最后编辑时间:

Version 4.0 (framework-1.0.0-rc.20)