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>