Skip to content

插件

插件(plugin)是一种可选的独立模块,它可以添加特定功能或特性,而无需修改主程序的代码。

Vue中使用插件

js
const app = createApp();
// 通过use方法来使用插件
app.use(router).use(pinia).use(ElementPlus).mount('#app')

Vue中制作插件

  1. 一个插件可以是一个拥有 install 方法的对象

    js
    const myPlugin = {
      install(app, options) {
        // 配置此应用
      }
    }
  2. 也可以直接是一个安装函数本身

    js
    const install = function(app, options){}

    安装方法接收两个参数:

    1. app:应用实例

    2. options:额外选项,这是在使用插件时传入的额外信息

      js
      app.use(myPlugin, {
        /* 可选的选项,会传递给 options */
      })

Vue中插件带来的增强包括:

  1. 通过 app.component 和 app.directive 注册一到多个全局组件或自定义指令
  2. 通过 app.provide 使一个资源注入进整个应用
  3. 向 app.config.globalProperties 中添加一些全局实例属性或方法
  4. 一个可能上述三种都包含了的功能库 (例如 vue-router)

例如:自定义组件库时,install 方法所做的事情就是往当前应用注册所有的组件

js
import Button from './Button.vue';
import Card from './Card.vue';
import Alert from './Alert.vue';

const components = [Button, Card, Alert];

const myPlugin = {
  install(app, options){
    // 这里要做的事情,其实就是引入所有的自定义组件
    // 然后将其注册到当前的应用里面
    components.forEach(com=>{
      app.component(com.name, com);
    })
  }
}

export default myPlugin;

实战:错误捕捉插件

在企业级应用开发中,经常需要一个 全局错误处理和日志记录插件,它能够帮助捕获和记录全局的错误信息,并提供一个集中化的日志记录机制。

我们的插件目标如下:

  1. 捕获全局的 Vue 错误未处理的 Promise 错误
  2. 将错误信息记录到控制台发送到远程日志服务器
  3. 提供一个 Vue 组件用于显示最近的错误日志。

先看下我们期望的使用方式:

js
//main.js
// 使用错误日志插件
app.use(ErrPlugin, {
  logToConsole: true, //是否向控制台输出
  remotoLogging: true, //是否向后端发送日志
  remoteUrl: "http://localhost:3000/log", //后端地址
});

1.编写ErrorLog.vue

vue
<template>
  <div v-if="errArr.length">
    <h2>错误日志</h2>
    <ul>
      <li v-for="(item, index) in errArr" :key="item.time">
        {{ item.message }}
      </li>
    </ul>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
// 用来存放错误日志信息
const errArr = ref([]);

onMounted(() => {
  const oldLogFn = console.error;
  // 重写错误日志函数,使用的时候会向errArr添加信息
  console.error = (...args) => {
    errArr.value.push({
      message: args[0],
      time: new Date().toDateString(),
    });
    oldLogFn.apply(console, args);
  };
});
</script>

<style scoped></style>

2.编写errLog.js插件

js
import ErrLog from "./ErrLog.vue";

//错误日志插件
export default {
  install(app, options = {}) {
    const defaultOptions = {
      logToConsole: true, //是否向控制台输出
      remotoLogging: false, //是否向后端发送日志
      remoteUrl: "", //后端地址
    };
    //进行参数归一化
    const config = { ...defaultOptions, ...options };

    // 捕捉全局vue错误,errorHandler用于捕获在 Vue 组件生命周期、渲染过程中发生的错误。
    app.config.errorHandler = (error, _vm, info) => {
      logErr(error, info);
    };
    // 捕捉未处理的promise错误
    window.addEventListener("unhandledrejection", (event) => {
      logErr(event.reason, "未处理的promise错误");
    });
    //错误处理函数
    function logErr(err, info) {
      // 向控制台输出
      if (config.logToConsole) {
        console.error(`[错误:${info}]`, err);
      }
      //调用后端记录错误日志接口
      if (config.remotoLogging && config.remoteUrl) {
        fetch(config.remoteUrl, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            error: err.message, // 错误消息
            stack: err.stack, // 错误堆栈
            info, // 具体错误说明信息
            time: new Date().toISOString(), // 记录时间
          }),
        }).catch(console.err);
      }
    }

    // 注册组件
    app.component("errLog", ErrLog);
  },
};

3.使用

vue
<template>
  <div>
    <!-- 抛出错误之后,页面会直接将记录的错误日志渲染 -->
    <button @click="craeteErr">抛出错误</button>

    <ErrLog />
  </div>
</template>

<script setup>
import { ref } from "vue";
import ErrLog from "./plugins/ErrorLog/ErrLog.vue";

const craeteErr = () => {
  throw Error("抛出错误了一个错误");
};
</script>

<style scoped></style>

注意:工程目录如下

sh
src
	--plugins
		--ErrLog.vue
		--errLog.js

-EOF-

MIT License