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>
相关推荐
一个懒人懒人3 分钟前
Promise async/await与fetch的概念
前端·javascript·html
Mintopia9 分钟前
Web 安全与反编译源码下的权限设计:构筑前后端一致的防护体系
前端·安全
输出输入11 分钟前
前端核心技术
开发语言·前端
Mintopia15 分钟前
Web 安全与反编译源码下的权限设计:构建前后端一体的信任防线
前端·安全·编译原理
林深现海36 分钟前
Jetson Orin nano/nx刷机后无法打开chrome/firefox浏览器
前端·chrome·firefox
EchoEcho1 小时前
深入理解 Vue.js 渲染机制:从声明式到虚拟 DOM 的完整实现
vue.js
黄诂多1 小时前
APP原生与H5互调Bridge技术原理及基础使用
前端
前端市界1 小时前
用 React 手搓一个 3D 翻页书籍组件,呼吸海浪式翻页,交互体验带感!
前端·架构·github
文艺理科生1 小时前
Nginx 路径映射深度解析:从本地开发到生产交付的底层哲学
前端·后端·架构
千寻girling1 小时前
主管:”人家 Node 框架都用 Nest.js 了 , 你怎么还在用 Express ?“
前端·后端·面试