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>
相关推荐
李伟_Li慢慢27 分钟前
12-mini版WebGLObjects
前端·three.js
李伟_Li慢慢32 分钟前
17-mini版WebGLBufferRenderer
前端·three.js
李伟_Li慢慢33 分钟前
16-mini版WebGLBackground
前端·three.js
李伟_Li慢慢40 分钟前
13-mini版WebGLProgram
前端·three.js
李伟_Li慢慢42 分钟前
14-mini版WebGLPrograms
前端·three.js
李伟_Li慢慢1 小时前
19-mini版WebGLRenderer
前端·three.js
李伟_Li慢慢1 小时前
10-mini版bindingStates
前端·three.js
এ慕ོ冬℘゜1 小时前
深入 JavaScript BOM:掌握 window 对象的窗口控制魔法
开发语言·javascript·ecmascript
李伟_Li慢慢1 小时前
08-BufferAttribute
前端·three.js