项目中自定义指令使用

针对项目中多处,图片url转文档流

方法一:自定义指令封装

引用(main.ts)

import Directives  from './directives'

app.use(Directives)

指令封装(directives/srcLoad.ts)

/**
 * src load
 * @Example v-srcLoad="imageUrl"
 */
 import request from '@/http/http'
 import type {
    
     Directive, DirectiveBinding } from 'vue';

 const srcLoad: Directive = {
    
    
 	// binding.value 里面是传递过来的数据
     mounted(el: MediaImage, binding: DirectiveBinding<any>) {
    
    
         request({
    
    
             method: 'get',
             url: '/cnap/assistant/v1/file/download',
             params: {
    
    
                bucketName: binding.value.split('/')[3],
                url: binding.value,
             },
             responseType: 'blob',
             timeout: 60 * 1000
         }).then((res: any) => el.src = window.URL.createObjectURL(new Blob([res], {
    
    type : 'image/png'}))).catch(ex => ex)
     }
 }
 
 export default srcLoad;

组件使用

  <a-space v-for="item in record.defectPhotos " :key="item.id">
	<img v-srcLoad="item.url" style="width: 100%;height:60px;object-fit: cover;" />
  </a-space> 

方法二: 封装成公共方法

import request from '@/http/http'

// 处理图片url-> 二进制流
export const getSrcLoad = (imageUrl: string) => {
    
    
  if(!imageUrl) return
  return request({
    
    
    method: 'get',
    url: '/cnap/assistant/v1/file/download',
    params: {
    
    
      bucketName: imageUrl.split('/')[3],
      url: imageUrl,
    },
    responseType: 'blob',
    timeout: 60 * 1000
  }).then((res: any) => window.URL.createObjectURL(new Blob([res], {
    
    type : 'image/png'}))).catch(ex => ex)
} 

使用(utils/srcLoad)

import {
    
     getSrcLoad } from "@/utils/srcLoad";

photoList.value.forEach(async e => e["url"] = await getSrcLoad(e.url))

猜你喜欢

转载自blog.csdn.net/MoXinXueWEB/article/details/130536074