vant 源码解析之 utils/index.ts 工具函数

本文介绍了一系列Vue相关的实用工具函数,包括环境判断、类型检查、路径解析等,旨在提高开发效率和代码质量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

源代码

import Vue from 'vue';

export { use } from './use';

export const isServer: boolean = Vue.prototype.$isServer;
//Vue 原型上自带的属性 判断上是否运行在服务端上

export function noop() {}

export function isDef(value: any): boolean {
  // value:any 表示传入的参数是任意类型  boolean 表示返回值是boolean类型
  return value !== undefined && value !== null;
  // 传入的值不能是undefined 也不能是null
}
//  in 15.686s  0.486s

export function isObj(x: any): boolean {
  //判断一个值是否是 对象类型
  // 传入的参数 是 any 任意类型i
  // 返回值是 boolean
  const type = typeof x;
  // typeof 判断数据类型
  // typeof 判断数据类型时 null 也是 object 所以 type 不能为null
  // 函数也是 对象
  return x !== null && (type === 'object' || type === 'function');
}

export function get(object: any, path: string): any {
  const keys = path.split('.');
  let result = object;

  keys.forEach(key => {
    result = isDef(result[key]) ? result[key] : '';
  });

  return result;
}

const camelizeRE = /-(\w)/g;//\w 表示数字字母吓下划线
export function camelize(str: string): string {
  return str.replace(camelizeRE, (_, c) => c.toUpperCase());
  //toUpperCase 将字母转换成 大写
  
}

export function isAndroid(): boolean {
  /* istanbul ignore next */
  return isServer ? false : /android/.test(navigator.userAgent.toLowerCase());
  // 只有在非服务端
  // 判断是否是安卓设备
}

export function isIOS(): boolean {
  /* istanbul ignore next */
  return isServer ? false : /ios|iphone|ipad|ipod/.test(navigator.userAgent.toLowerCase());
  // 只有在非服务端
  //判断是否是 ios设备
}

export function range(num: number, min: number, max: number): number {
  // Math.max 返回一组数中的最大者
  // Math.min 返沪一组数种的最小者
  return Math.min(Math.max(num, min), max);
}

export function isInDocument(element: HTMLElement): boolean {
  // 在ts j中 dom 节点的type类型是 HTMLElement
  // 返回值是boolean
  return document.body.contains(element);
  // document.body 节点 是否包含目标节点
}

<template> <div class="news-images"> <div v-for="(img, idx) in images" :key="idx" class="news-img-wrap"> <!-- 上传进度显示 --> <div v-if="img.status === 'uploading'" class="progress-overlay"> <van-circle v-model:current-rate="img.progress" :rate="100" :speed="10" size="120rem" :stroke-width="20" stroke-linecap="round" class="progress" > <span class="progress-text">{{ img.progress }}%</span> </van-circle> </div> <!-- 错误状态显示 --> <div v-if="img.status === 'error'" class="error-overlay"> <van-icon name="warning" size="32rem" color="#ff4444" /> <span>上传失败</span> <van-button type="primary" size="small" @click="reUpload(idx)" style="margin-top: 16rem">重新上传</van-button> </div> <img :src="img.url" class="news-img" /> <div class="img-close" @click="removeImg(idx)"> <van-icon name="cross" size="32rem" color="#fff" /> </div> </div> <div v-if="images.length < maxCount" class="news-img-add" @click="onAddImg"> <van-icon name="plus" size="64rem" color="#bbb" /> </div> <!-- 隐藏的文件选择器 --> <input ref="fileInput" type="file" multiple accept="image/*" style="display: none" @change="handleFileChange" /> </div> </template> <script setup lang="ts"> import { apis } from '@/api' import System from '@/utils/System' import { showToast } from 'vant' import { ref, onUnmounted } from 'vue' const emit = defineEmits(['update:modelValue']) const props = defineProps({ autoUpload: { type: Boolean, default: true }, maxCount: { type: Number, default: 9 }, modelValue: { type: Array as () => imgageItem[], default: () => [] } }) interface imgageItem { url: string progress: number status: 'pending' | 'uploading' | 'success' | 'error' file?: File } const fileInput = ref<HTMLInputElement | null>(null) const images = ref<imgageItem[]>(props.modelValue) const onAddImg = () => { fileInput.value?.click() } const removeImg = async (idx: number) => { images.value.splice(idx, 1) emit('update:modelValue', [...images.value]) } // const handleFileChange = async (e: Event) => { // const target = e.target as HTMLInputElement // const files = target.files // if (!files || files.length === 0) return // for (const file of Array.from(files)) { // if (images.value.length >= props.maxCount) break // try { // const reader = new FileReader() // console.log("🚀 ~ handleFileChange ~ reader:", reader) // reader.onload = (ev) => { // if (typeof ev.target?.result === 'string') { // const index = images.value.length // images.value.push({ // url: ev.target.result, // 临时预览URL // progress: 0, // status: 'pending', // file: file // }) // console.log("🚀 ~ handleFileChange ~ images.value:", images.value) // if (props.autoUpload) { // uploadFile(file, index) // } // reader.readAsDataURL(file) // } // } // // 清空 input // ;(e.target as HTMLInputElement).value = '' // // 更新父组件 // emit('update:modelValue', [...images.value]) // } catch (error) { // System.toast('图片处理失败') // console.error('文件处理错误:', error) // } // } // // 清空文件选择器 // ;(e.target as HTMLInputElement).value = '' // } const handleFileChange = (e: Event) => { const files = (e.target as HTMLInputElement).files if (files && files.length > 0) { Array.from(files).forEach((file) => { if (images.value.length >= 6) return const reader = new FileReader() reader.onload = (ev) => { if (typeof ev.target?.result === 'string') { const index = images.value.length images.value.push({ url: ev.target.result, // 临时预览URL progress: 0, status: 'pending', file: file }) // 开始上传 if (props.autoUpload) { uploadFile(file, index) } } } reader.readAsDataURL(file) }) emit('update:modelValue', [...images.value]) // 清空 input ;(e.target as HTMLInputElement).value = '' } } const uploadFile = async (file: File, index: number) => { // try { images.value[index].status = 'uploading' // 调用API上传 const formData = new FormData() formData.append("file",file) const res: any = await apis.uploadFile({ file: formData.get('file') }, (progressEvent: { loaded: number; total: number }) => { if (progressEvent.total > 0) { images.value[index].progress = Math.round((progressEvent.loaded / progressEvent.total) * 100) } }) if (res.code === 200) { images.value[index].status = 'success' images.value[index].url = res.data } else { images.value[index].status = 'error' System.toast('图片上传失败') } emit('update:modelValue', [...images.value]) // } catch (error) { // images.value[index].status = 'error' // System.toast('图片上传失败') // console.error('上传错误:', error) // emit('update:modelValue', [...images.value]) // } } // 自动上传全部待上传图片 const autoUploadAll = () => { images.value.forEach((img, index) => { if (img.status === 'pending' && img.file) { uploadFile(img.file, index) } }) } // 重新上传指定失败图片 const reUpload = (index: number) => { if (images.value[index].status !== 'error' || !images.value[index].file) return images.value[index].status = 'pending' uploadFile(images.value[index].file!, index) } // 组件卸载时清理临时文件 onUnmounted(async () => {}) defineExpose({ autoUploadAll, reUpload }) </script> <style lang="less" scoped> .news-images { display: flex; flex-wrap: wrap; gap: 18.5rem; margin-bottom: 48rem; .news-img-wrap { position: relative; width: 216rem; height: 216rem; border-radius: 23rem; overflow: hidden; margin-bottom: 32rem; // 新增,保证多行间距 .progress-overlay { position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.5); display: flex; justify-content: center; align-items: center; z-index: 2; .progress { display: flex; align-items: center; justify-content: center; } .progress-text { color: #fff; font-size: 24rem; } } .error-overlay { position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.5); display: flex; flex-direction: column; justify-content: center; align-items: center; z-index: 2; span { color: #fff; font-size: 24rem; margin-top: 8rem; } } .news-img { width: 100%; height: 100%; object-fit: cover; border-radius: 24rem; } .img-close { position: absolute; top: 8rem; right: 8rem; background: rgba(0, 0, 0, 0.4); border-radius: 50%; width: 40rem; height: 40rem; display: flex; align-items: center; justify-content: center; cursor: pointer; z-index: 3; } } .news-img-add { width: 216rem; height: 216rem; background: #f6f6f6; border-radius: 23rem; display: flex; align-items: center; justify-content: center; cursor: pointer; margin-bottom: 32rem; // 保持添加按钮与图片对齐 .van-icon { font-weight: bold; } } } </style> 这个代码帮我解决
最新发布
07-05
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值