vue3 + ts:开发插件 / Plugins / 注册全局实例 / 在 template 与 setup 中使用 / provide、inject

发布于:2024-12-08 ⋅ 阅读:(142) ⋅ 点赞:(0)

一、理解插件 / Plugins

https://cn.vuejs.org/guide/reusability/plugins.html

理解一

一个插件通常是一个对象,包含一个 install 方法。install 方法在插件注册时被调用,用于将插件的功能和特性添加到 Vue 应用实例中。

理解二

插件 (Plugins) 是一种能为 Vue 添加全局功能的工具代码。

一个插件可以是拥有install()方法的对象,也可以直接是一个安装函数本身,安装函数会接收到安装它的应用实例和传递给app.use()的额外选项作为参数。

二、插件发挥作用的常见场景

2.1、插件没有严格定义的使用范围,但是插件发挥作用的常见场景主要包括以下几种

2.2、通过 app.component() 和 app.directive() 注册一到多个全局组件或自定义指令。

2.3、通过 app.provide() 使一个资源可被注入进整个应用。

2.4、向 app.config.globalProperties 中添加一些全局实例属性或方法

一个可能上述三种都包含了的功能库 (例如 vue-router)。

三、实例

3.1、MyPlugin.ts

// MyPlugin.ts
import { App } from 'vue';
import HelloWorld from '@v3/components/HelloWorld.vue'
export default {
  install(app: App, options) {
    // 插件逻辑
    console.log('MyPlugin is installed with options:', options);

    // 你可以在这里添加全局方法、指令、混入等
    // 示例:添加全局方法
    app.config.globalProperties.$myMethod = () => {
      return 'This is a method from MyPlugin!'
      console.log('This is a method from MyPlugin!');
    };

    // provide inject 方法
    app.provide('myMethodP', function() {
        console.log('This is a global method');
    })

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

    // 示例:添加全局混入
    app.mixin({
      created() {
        console.log('This is a mixin from MyPlugin!');
      }
    });

    // 示例:添加全局组件-未生效-待查明
    // app.component('MyComponent', {
    //   template: '<div>This is a component from MyPlugin!</div>'
    // });
    // 生效
    app.component('MyComponent', HelloWorld);
  }
};

3.2、main.ts

import mi18n from '@v3/plugins/MyPlugin'
...
app.use(mi18n)

四、全局方法

4.1、template 使用

<template>
    <div class="container">
        <div>{{ $myMethod() }}</div>
    </div>
</template>

4.2、组合式 API / setup 内使用

<script setup lang="ts">
import { getCurrentInstance } from 'vue'
let internalInstance = getCurrentInstance()
let myMethod = internalInstance && internalInstance.appContext.config.globalProperties.$myMethod
</script>

4.3、 选项式 API

<script>
export default {
  methods: {
    usePluginMethod() {
      // 调用插件中的全局方法
      this.$myMethod();
    }
  }
};
</script>

五、全局指令

<template>
  <div>
    <h1 v-my-directive="'red'">Hello, Snow!</h1>
    <MyComponent />
    <button @click="usePluginMethod">Use Plugin Method</button>
  </div>
</template>

六、全局混入

全局混入会自动应用到所有组件中,因此在 <script setup> 组件中,你无需显式地引入或使用它们。混入的生命周期钩子和方法将自动与组件的生命周期钩子和方法合并

七、全局组件

<template>
  <MyComponent />
</template>

八、provide、inject

<script setup lang="ts">
import { inject } from 'vue'
const myMethodP = inject('myMethodP')
console.log('54', myMethodP)
</script>

九、欢迎交流指正

十、参考链接

vue3-vite-ts:编写Rollup插件并使用 / 优化构建过程_vite 中 rollup-plugin-dts-CSDN博客

04-Vue3插件介绍讲解_哔哩哔哩_bilibili

https://cn.vuejs.org/api/application.html#app-config-globalproperties

Vue3

vue3注册添加全局实例属性的方法,如何在setup函数中调用-阿里云开发者社区


网站公告

今日签到

点亮在社区的每一天
去签到