【Vue3第二十六章】自定义Hooks & 编写Vue3插件

1. 自定义Hooks

Vue3 自定义Hook,主要用来处理复用代码逻辑的一些封装,这个在vue2 就已经有一个东西是Mixins。
mixins就是将这些多个相同的逻辑抽离出来,各个组件只需要引入mixins,就能实现一次写代码,多组件受益的效果。
在这里插入图片描述

1.1 和 Mixin 的对比​
Vue 2 的用户可能会对 mixins 选项比较熟悉。它也让我们能够把组件逻辑提取到可复用的单元里。然而 mixins 有三个主要的短板:

不清晰的数据来源:当使用了多个 mixin 时,实例上的数据属性来自哪个 mixin 变得不清晰,这使追溯实现和理解组件行为变得困难。这也是我们推荐在组合式函数中使用 ref + 解构模式的理由:让属性的来源在消费组件时一目了然。

命名空间冲突:多个来自不同作者的 mixin 可能会注册相同的属性名,造成命名冲突。若使用组合式函数,你可以通过在解构变量时对变量进行重命名来避免相同的键名。

隐式的跨 mixin 交流:多个 mixin 需要依赖共享的属性名来进行相互作用,这使得它们隐性地耦合在一起。而一个组合式函数的返回值可以作为另一个组合式函数的参数被传入,像普通函数那样。

基于上述理由,我们不再推荐在 Vue 3 中继续使用 mixin。保留该功能只是为了项目迁移的需求和照顾熟悉它的用户。

1.2 和无渲染组件的对比
组合式函数相对于无渲染组件的主要优势是:组合式函数不会产生额外的组件实例开销。当在整个应用中使用时,由无渲染组件产生的额外组件实例会带来无法忽视的性能开销。

我们推荐在纯逻辑复用时使用组合式函数,在需要同时复用逻辑和视图布局时使用无渲染组件。

1.3 和 React Hooks 的对比
如果你有 React 的开发经验,你可能注意到组合式函数和自定义 React hooks 非常相似。组合式 API 的一部分灵感正来自于 React hooks,Vue 的组合式函数也的确在逻辑组合能力上与 React hooks 相近。然而,Vue 的组合式函数是基于 Vue 细粒度的响应性系统,这和 React hooks 的执行模型有本质上的不同

1.4 自定义 Hooks 案例代码演示

import { onMounted } from 'vue'
 
 
type Options = {
    el: string
}
 
type Return = {
    Baseurl: string | null
}
export default function (option: Options): Promise<Return> {
 
    return new Promise((resolve) => {
        onMounted(() => {
            const file: HTMLImageElement = document.querySelector(option.el) as HTMLImageElement;
            file.onload = ():void => {
                resolve({
                    Baseurl: toBase64(file)
                })
            }
 
        })
 
 
        const toBase64 = (el: HTMLImageElement): string => {
            const canvas: HTMLCanvasElement = document.createElement('canvas')
            const ctx = canvas.getContext('2d') as CanvasRenderingContext2D
            canvas.width = el.width
            canvas.height = el.height
            ctx.drawImage(el, 0, 0, canvas.width,canvas.height)
            console.log(el.width);
            
            return canvas.toDataURL('image/png')
 
        }
    })
}

数字化管理平台
Vue3+Vite+VueRouter+Pinia+Axios+ElementPlus
Vue权限系统案例
个人博客地址

2. 编写Vue3插件

插件 (Plugins) 是一种能为 Vue 添加全局功能的工具代码。
一个插件可以是一个拥有 install() 方法的对象,也可以直接是一个安装函数本身。安装函数会接收到安装它的应用实例和传递给 app.use() 的额外选项作为参数

定义插件

import {
    
     createApp } from 'vue'

const app = createApp({
    
    })

app.use(myPlugin, {
    
    
  /* 可选的选项 */
})

使用插件

const myPlugin = {
    
    
  install(app, options) {
    
    
    // 配置此应用
  }
}

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

  • 通过 app.component() 和 app.directive() 注册一到多个全局组件或自定义指令。
  • 通过 app.provide() 使一个资源可被注入进整个应用。
  • 向 app.config.globalProperties 中添加一些全局实例属性或方法
  • 一个可能上述三种都包含了的功能库 (例如 vue-router)。

示例代码:尝试自定义一个 Loading 插件
Loading.vue

<template>
    <div v-if="isShow" class="loading">
        <div class="loading-content">Loading...</div>
    </div>
</template>
    
<script setup lang='ts'>
import {
    
     ref } from 'vue';
const isShow = ref(false)//定位loading 的开关
 
const show = () => {
    
    
    isShow.value = true
}
const hide = () => {
    
    
    isShow.value = false
}
//对外暴露 当前组件的属性和方法
defineExpose({
    
    
    isShow,
    show,
    hide
})
</script>
    
<style scoped lang="less">
.loading {
    
    
    position: fixed;
    inset: 0;
    background: rgba(0, 0, 0, 0.8);
    display: flex;
    justify-content: center;
    align-items: center;
    &-content {
    
    
        font-size: 30px;
        color: #fff;
    }
}
</style>

Loading.ts

import {
    
      createVNode, render, VNode, App } from 'vue';
import Loading from './index.vue'
 
export default {
    
    
    install(app: App) {
    
    
        //createVNode vue提供的底层方法 可以给我们组件创建一个虚拟DOM 也就是Vnode
        const vnode: VNode = createVNode(Loading)
        //render 把我们的Vnode 生成真实DOM 并且挂载到指定节点
        render(vnode, document.body)
        // Vue 提供的全局配置 可以自定义
        app.config.globalProperties.$loading = {
    
    
            show: () => vnode.component?.exposed?.show(),
            hide: () => vnode.component?.exposed?.hide()
        }
 
    }
}

Main.ts

import Loading from './components/loading'
 
 
let app = createApp(App)
 
app.use(Loading)
 
 
type Lod = {
    show: () => void,
    hide: () => void
}
//编写ts loading 声明文件放置报错 和 智能提示
declare module '@vue/runtime-core' {
    export interface ComponentCustomProperties {
        $loading: Lod
    }
}
 
 
 
app.mount('#app')

使用方法

<template>
 
  <div></div>
 
</template>
 
<script setup lang='ts'>
    import { ref,reactive,getCurrentInstance} from 'vue'
    const  instance = getCurrentInstance()  
    instance?.proxy?.$Loading.show()
    setTimeout(()=>{
      instance?.proxy?.$Loading.hide()
    },5000)


    // console.log(instance)
    </script>
    <style>
    *{
      padding: 0;
      margin: 0;
    }
</style>

Vue.use 源码手写

import type { App } from 'vue'
import { app } from './main'
 
interface Use {
    install: (app: App, ...options: any[]) => void
}
 
const installedList = new Set()
 
export function MyUse<T extends Use>(plugin: T, ...options: any[]) {
    if(installedList.has(plugin)){
      return console.warn('重复添加插件',plugin)
    }else{
        plugin.install(app, ...options)
        installedList.add(plugin)
    }
}

插件中的 Provide / Inject
在插件中,我们可以通过 provide 来为插件用户供给一些内容。让任何组件都能使用这些内容。
详细使用详见官网 Provide/Inject 描述。

猜你喜欢

转载自blog.csdn.net/qq_39335404/article/details/130987039