Vue3 中使用组合式API和依赖注入实现自定义公共方法

组合式API

1.在项目根目录 src 文件夹下创建文件夹 utils ,创建 index.js 文件

2.抛出想要对外暴露的方法,以下是一个判断数据类型的方法

复制代码
export function getType(params) {
  // 判断是否是基本类型
  let res = typeof params
  if (res !== 'object') {
    return res
  } else {
    // 判断复杂类型
    const typeStr = Object.prototype.toString.call(params)
    const match = typeStr.match(/\[object (\w+)\]/)
    if (match) {
      return match[1].toLowerCase()
    }
    return 'unknown'
  }
}

3.在 main.js 文件写如下代码,其中注释已附上

复制代码
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
// 引入方法文件
import * as utils from './utils'
// 创建vue实例
const app = createApp(App)
// 全局挂载
app.config.globalProperties.$utils = utils
app.mount('#app')

4.在组件中使用

复制代码
<script setup>
import { ref, onMounted, getCurrentInstance } from 'vue'

defineProps({
  msg: String,
})

onMounted(() => {
  // 使用组合式API获取当前实例
  const instance = getCurrentInstance()
  if (instance && instance.proxy) {
     let res = instance.proxy.$utils.getType(1)
     console.log('====================================')
     console.log(res)
     console.log('====================================')
  }
})
</script>

<template>
  <div>{
  
  { msg }}</div>
</template>

<style scoped>
.read-the-docs {
  color: #888;
}
</style>

依赖注入

1、2步骤是一样的,不过多赘述

3.在 main.js 文件写如下代码,其中注释已附上

复制代码
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
// 引入方法文件
import * as utils from './utils'
// 创建vue实例
const app = createApp(App)
// 依赖注入
app.provide('utils', utils)
app.mount('#app')

4.在组件中使用

复制代码
<script setup>
import { ref, onMounted, inject } from 'vue'

defineProps({
  msg: String,
})

onMounted(() => {
  // 依赖注入
  const utils = inject('utils')
  let res = utils.getType(123)
  console.log('====================================')
  console.log(res)
  console.log('====================================')
})
</script>

<template>
  <div>{
  
  { msg }}</div>
</template>

<style scoped>
.read-the-docs {
  color: #888;
}
</style>
相关推荐
ji_shuke4 分钟前
Vue3 前端批量打印 PDF/图片踩坑记:跨域、合并打印、对话框闪退与按钮一直 loading
前端·pdf·状态模式·pdf打印
李伟_Li慢慢4 分钟前
06-mini版WebGLState
前端·three.js
李伟_Li慢慢9 分钟前
04-three.js的渲染流程概览
前端·three.js
李伟_Li慢慢10 分钟前
07-WebGLProperties
前端·three.js
爱勇宝10 分钟前
AI 都能写代码了,还要学计算机吗?
前端·后端·程序员
石像鬼₧魂石14 分钟前
【Y2Ksoft】四季贵州水世界乐园管理系统 —— 玻璃拟态 · 单文件HTML · 开箱即用
前端·html
涛涛ing17 分钟前
尤雨溪宣布:Vue 3.6 发布、Vue 4.0 启动、Vite 8 已落地
前端
李伟_Li慢慢19 分钟前
05-mini版材质
前端·three.js
学以智用22 分钟前
HTTP 请求头 Headers 完整详解
前端·后端
李伟_Li慢慢22 分钟前
03-threejs架构原理浅析
前端·three.js