vue中封装的函数常用方法(持续更新)

封装图片懒加载 自定义指令

TypeScript 复制代码
import { App } from 'vue'
import { useIntersectionObserver } from '@vueuse/core'
import defaultImg from '@/assets/images/200.png'

export default {
  install(app: App) {
    app.directive('lazy', {
      // el => v-lazy 写到哪儿,el 就是谁
      // binding => binding.value
      // v-lazy="xxx" => binding.value => xxx
      mounted(el, binding) {
        const { stop } = useIntersectionObserver(el, ([{ isIntersecting }]) => {
          if (isIntersecting) {
            // 把传过来的地址给图片真正的 src 属性
            el.src = binding.value
            // 加载失败给一个默认图片
            el.onerror = function () {
              this.src = defaultImg
            }
            // 停止监听
            stop()
          }
        })
      },
    })
  },
}

1.封装API

第一步

第二步

第三步

2.注册全局工具组件

使用场景:想让组件全局可用,尤其是第三方插件使用时

步骤一:

步骤二:

3.封装全局函数

使用场景:有些逻辑处理函数代码量很大,且具有独特功能(如日期处理函数,数组转树函数),可能以后别的地方要用,就封装起来,方便。

步骤一:

步骤二:

  1. 为了减少页面代码量的封装

使用场景:很多,这里以注册路由表举例,理解封装思想

步骤一:

步骤二:

封装函数 方便调用

1.获取时间(一般时间选择器默认时间用到)

javascript 复制代码
//获取当前时间,day为number,getDay(-1):昨天的日期;getDay(0):今天的日期;getDay(1):明天的日期;
getDay(day) {
      let today = new Date(),
        targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day;
      today.setTime(targetday_milliseconds);
      let tYear = today.getFullYear(),
        tMonth = today.getMonth(),
        tDate = today.getDate(),
        tHour = today.getHours(),
        tMinute = today.getMinutes(),
        tSeconds = today.getSeconds();
      tMonth = this.doHandleMonth(tMonth + 1);
      tDate = this.doHandleMonth(tDate);
      tHour = this.doHandleMonth(tHour);
      tMinute = this.doHandleMonth(tMinute);
      tSeconds = this.doHandleMonth(tSeconds);
      return tYear + '-' + tMonth + '-' + tDate + ' ' + tHour + ':' + tMinute + ':' + tSeconds;

2.判断数据是否是json

javascript 复制代码
//判断数据源是不是json数据
    isJsonString(str) {
      try {
        if (typeof JSON.parse(str) == 'object') {
          return true;
        }
      } catch (e) {
        console.log('e', e);
      }
      return false;
    },

3.获取指定位置的天气信息:

javascript 复制代码
//获取天气信息
    getWeather() {
      axios
        .get('https://geoapi.qweather.com/v2/city/lookup', {
          params: {
            location: '杭州市',
            key: '',
            _t: new Date().getTime()
          },
        })
        .then(({ data: res }) => {
          // console.log(res);
          if (res.code != 200) {
            return this.$message.error('获取地理位置定位ID(locationID)失败');
          }
          if (res.location.length > 0) {
            axios
              .get('https://devapi.qweather.com/v7/weather/now', {
                params: {
                  location: res.location[0].id,
                  key: '',
                  _t: new Date().getTime()
                },
              })
              .then(({ data: res1 }) => {
                // console.log('res1', res1);
                if (res1.status != 0) {
                  return this.$message.error('获取天气信息失败');
                }
                this.$set(this.weatherInfo, 'wea', res1.now.text);
                this.$set(this.weatherInfo, 'tem', res1.now.temp);
                this.$set(this.weatherInfo, 'wea_img', res1.fxLink);
              })
              .catch((error) => {
                console.log(error);
                return false;
              });
          } else {
            return this.$message.error('无法获取地理位置定位ID(locationID)');
          }
        })
        .catch((e) => {
          console.log(e);
          return false;
        });
    },

4.判断浏览器类型

javascript 复制代码
/**
 * 判断浏览器的类型
 */
export function browserType() {
    var userAgent = navigator.userAgent.toLowerCase();
    var testCenter = {
        ie: function isIE() { //ie?
            if (!!window.ActiveXObject || "ActiveXObject" in window)
                return true;
            else
                return false;
        },
        edge: () => {
            return /dge/.test(userAgent)
        },
        chrome: () => {
            return /chrome/.test(userAgent)
        },
        safari: () => {
            return /safari/.test(userAgent) && !(/chrome/.test(userAgent))
        },
        opera: () => {
            return /opera/.test(userAgent)
        },
        msie: () => {
            return /msie/.test(userAgent) && !/opera/.test(userAgent)
        },
        mozilla: () => {
            return /mozilla/.test(userAgent) && !/(compatible|webkit)/.test(userAgent)
        }
    };
    var browserObj = {};
    for (var k in testCenter) {
        var result = testCenter[k]();
        var version = (userAgent.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/) || [])[1];
        if (result) {
            browserObj.browser = k;
            browserObj.version = version;
            return browserObj;
        }
    }
}

5.判断object类

javascript 复制代码
//判断Object数据类型
export function isType(obj) {
    var type = Object.prototype.toString.call(obj);
    if (type == '[object Array]') {
        return 'Array';
    } else if (type == '[object Object]') {
        return "Object"
    } else {
        return 'param is no object type';
    }
}

6.将扁平的数据转化为树形结构

javascript 复制代码
// 将平铺的数据转化为树形结构的数据
export function tranListTotreeList(list) {
  const map = {}
  list.forEach(item => {
    item.children = []
    map[item.id] = item
// 把item.id作为属性名 吧item作为属性值
// id 2c: {id: '2c', pid: '', name: '财务部', children: Array(2)}
  })
  console.log(list)
  console.log(map)
  // 3. 遍历数据,生成最终的树形结构
  const treeList = []
  list.forEach(item => {
    // 1. 找关系,找出父级的对象,如果找到父级对象,将item,添加父级的对象的chilren里面
    // 2. 判断是否是子级数据对象
    const parent = map[item.pid]
    if (parent) {
      // 子级数据对象,二级数据加入到父级对象parent的chilren中
      parent.children.push(item)
    } else {
      // 3. 一级的数据对象,一级数据对象 直接加入到treeList中
      treeList.push(item)
    }
  })
  return treeList
}

封装日期函数,将当前时间,格式为 2025-11-19 19:47:16

javascript 复制代码
// 获取格式化的当前时间(每次调用时重新计算)
function getFormattedTime(): string {
  const now = new Date()
  const localTime = new Date(now.getTime() - now.getTimezoneOffset() * 60000)
  return localTime.toISOString().replace('T', ' ').substring(0, 19)
}
相关推荐
Light6016 小时前
点燃变革:领码SPARK融合平台如何重塑OA,开启企业智慧协同新纪元?
大数据·分布式·spark
2401_8784545316 小时前
浏览器工作原理
前端·javascript
Guheyunyi16 小时前
智慧消防管理系统如何重塑安全未来
大数据·运维·服务器·人工智能·安全
写代码的【黑咖啡】17 小时前
如何在大数据数仓中搭建数据集市
大数据·分布式·spark
华清远见成都中心17 小时前
成都理工大学&华清远见成都中心实训,助力电商人才培养
大数据·人工智能·嵌入式
by__csdn18 小时前
Vue3 setup()函数终极攻略:从入门到精通
开发语言·前端·javascript·vue.js·性能优化·typescript·ecmascript
梦里不知身是客1118 小时前
flume防止数据丢失的方法
大数据·flume
一条可有可无的咸鱼18 小时前
企业招聘信息,企业资讯进行公示
java·vue.js·spring boot·uni-app
Luna-player19 小时前
在前端中,<a> 标签的 href=“javascript:;“ 这个是什么意思
开发语言·前端·javascript
lionliu051919 小时前
js的扩展运算符的理解
前端·javascript·vue.js