vue.js

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > vue.js > Vue3全局公共函数

Vue3实现全局公共函数的完整方案(创建、挂载、引用、使用)

作者:还是大剑师兰特

本文详细介绍了如何在Vue3项目中创建、挂载、引用和使用全局公共函数,包括标准目录结构、创建公共函数、全局注册、页面使用以及规范,通过本文,新手开发者可以快速搭建企业级规范工具库,需要的朋友可以参考下

给你最标准、企业级、新手一看就会的全局函数方案,包含:文件夹位置 → 创建方法 → 全局注册 → 页面使用 → 实战示例。把 文件夹规范、注册、引用、页面使用、注意事项、实战场景全部一次性讲透,你照着做就能搭建企业级规范工具库。

一、标准目录结构(必须这样建)

src/
├── utils/             【工具函数根目录】
│   ├── index.js       【主入口:统一导出所有函数】
│   ├── olUtils.js     【分文件:OpenLayers地图专用工具】
│   ├── format.js      【分文件:格式化工具】
│   └── filter.js      【分文件:数据过滤工具】
├── main.js            【全局注册入口】
└── src/xxx.vue        业务页面

为什么要分文件?

二、第一步:创建公共函数

1. 创建地图工具:src/utils/olUtils.js

// OpenLayers SVG 图标生成
export function getSvgMarker(color = '#ff4400') {
  return `data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 100 100">
    <circle cx="50" cy="50" r="40" fill="${color}" stroke="#fff" stroke-width="5"/>
  </svg>`.replace(/\s+/g, '')
}
// 坐标转换
export function wgs84ToMercator(lon, lat) {
  return import.meta.env.VITE_APP_PROJECTION === 'EPSG:3857'
    ? [lon, lat]
    : fromLonLat([lon, lat])
}

2. 创建数据过滤工具:src/utils/filter.js

// 根据配置 isShow 过滤对象字段
export function filterByShowConfig(data, config) {
  const result = {}
  for (const key in data) {
    if (config[key] && config[key].isShow === true) {
      result[key] = data[key]
    }
  }
  return result
}

3. 统一出口:src/utils/index.js

// 统一导出所有工具函数
export * from './olUtils'
export * from './filter'

三、第二步:全局注册(两种方式)

方式1:挂载到全局(所有页面不用 import)

main.js

import { createApp } from 'vue'
import App from './App.vue'
import * as $utils from './utils/index'  // 引入

const app = createApp(App)

app.config.globalProperties.$utils = $utils  // 全局挂载

app.mount('#app')

挂载后全局可访问:

方式2:配置路径别名(最舒服)

vite.config.js

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'

export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      '@': path.resolve(__dirname, 'src'),
      '@utils': path.resolve(__dirname, 'src/utils')
    }
  }
})

之后可以这样引用:

import { getSvgMarker } from '@utils'

四、第三步:在页面中如何使用?(三种用法)

用法1:<script setup>最推荐(直接 import)

<script setup>
// 直接导入需要的函数
import { getSvgMarker, filterByShowConfig } from '@utils'

// 使用 SVG
const marker = getSvgMarker('blue')

// 使用数据过滤
const A = {}
const B = {}
const filteredData = filterByShowConfig(A, B)
</script>

用法2:使用全局挂载(不用 import)

<script setup>
import { getCurrentInstance } from 'vue'
const { proxy } = getCurrentInstance()

// 直接使用全局函数
const icon = proxy.$utils.getSvgMarker('red')
const result = proxy.$utils.filterByShowConfig(A, B)
</script>

用法3:选项式 API

<script>
export default {
  mounted() {
    const icon = this.$utils.getSvgMarker('green')
  }
}
</script>

五、全局函数使用规范(企业级)

1. 工具函数必须:

2. 哪些功能适合写进全局工具?

3. 不适合写进全局:

六、给你一套直接放进你项目的终极模板

1.src/utils/olUtils.js(地图图标、坐标)

import { fromLonLat } from 'ol/proj'

// SVG 地图标点
export function getSvgIcon(color = '#ff4400') {
  return `data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"><circle cx="16" cy="16" r="14" fill="${color}" stroke="#fff" stroke-width="2"/></svg>`
}

// 坐标转墨卡托
export function toMercator(lon, lat) {
  return fromLonLat([Number(lon), Number(lat)])
}

2.src/utils/filter.js(你的字段过滤)

export function filterByConfig(data, config) {
  let res = {}
  for (let k in data) {
    if (config[k]?.isShow) res[k] = data[k]
  }
  return res
}

3.src/utils/index.js

export * from './olUtils'
export * from './filter'

4.main.js

import * as $utils from './utils'
app.config.globalProperties.$utils = $utils

5. 任意页面使用

<script setup>
import { getSvgIcon, filterByConfig } from '@utils'

// 地图图标
const icon = getSvgIcon('#0088ff')

// 数据过滤
const filtered = filterByConfig(A, B)
</script>

七、一句话总结(最关键)

以上就是Vue3实现全局公共函数的完整方案(创建、挂载、引用、使用)的详细内容,更多关于Vue3全局公共函数的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文