Vue3.0:编写插件

MyDirective文件下 MyDirective.ts、index.ts 两个文件

添加 MyDirective.ts 文件

复制代码
import type { Plugin } from 'vue';

const MyPlugin: Plugin = {
  install(app, options) {
    // 添加全局组件
    app.component('MyComponent', {
      // 组件定义...
    });

    // 添加全局指令
    app.directive('my-color', {
      // 指令定义...
      mounted(el, binding) {
        el.style.color = binding.value;
      }
    });

    // 添加全局方法或属性
    app.config.globalProperties.$myMethod = (text: any) => {
      // 方法实现...
      console.log(text);
    };

    // 还可以根据 options 参数来配置插件
    console.log('MyPlugin options:', options);
  },
};

export default MyPlugin;

index.ts

复制代码
import MyDirective from './MyDirective';
export default {
  install: (app: any, options?: any) => {
    app.use(MyDirective);
  }
};

main.ts

复制代码
import MyColor from './plugin/MyDirective/index';
import { createApp } from 'vue';
const app = createApp(App);
app.use(MyColor);

使用

复制代码
<template>
  <div v-my-color="someValue1">Hello, world!!!!!!!!!</div>
  <div>{{ $myMethod(111111) }}</div>
</template>

<script setup>
import { getCurrentInstance, onMounted } from 'vue';
const instance = getCurrentInstance();
onMounted(() => {
  myMethod(222222);
});
</script>
相关推荐
持久的棒棒君2 小时前
npm安装electron下载太慢,导致报错
前端·electron·npm
渔舟唱晚@4 小时前
大模型数据流处理实战:Vue+NDJSON的Markdown安全渲染架构
vue.js·大模型·数据流
crary,记忆4 小时前
Angular微前端架构:Module Federation + ngx-build-plus (Webpack)
前端·webpack·angular·angular.js
漂流瓶jz5 小时前
让数据"流动"起来!Node.js实现流式渲染/流式传输与背后的HTTP原理
前端·javascript·node.js
SamHou05 小时前
手把手 CSS 盒子模型——从零开始的奶奶级 Web 开发教程2
前端·css·web
我不吃饼干5 小时前
从 Vue3 源码中了解你所不知道的 never
前端·typescript
开航母的李大5 小时前
【中间件】Web服务、消息队列、缓存与微服务治理:Nginx、Kafka、Redis、Nacos 详解
前端·redis·nginx·缓存·微服务·kafka
Bruk.Liu5 小时前
《Minio 分片上传实现(基于Spring Boot)》
前端·spring boot·minio
鱼樱前端6 小时前
Vue3+d3-cloud+d3-scale+d3-scale-chromatic实现词云组件
前端·javascript·vue.js
q_19132846956 小时前
基于Springboot+Vue的办公管理系统
java·vue.js·spring boot·后端·intellij idea