使用Map自定义文件标签

需求场景

之前实习的时候,有个场景,需要根据每篇文章所包含的附件文件类型显示对应的Tag,类似于elementUI的tag标签,并且每种文件格式对应不同的配置样式。

elementUI-Tag

看到这个,一下子就想到了键/值对,那不就是Object了嘛。但是在ES6以前,在js中实现“键/值”式存储可以使用Object来方便高效的完成,也就是使用对象属性作为键,再使用属性来引用值。作为ES6的新增特性,Map是一种新的集合类型,为这门语言带来了真正的键/值存储机制。于是,在此,就使用Map来实现此功能啦。

FileTag组件

首先,子组件开放 fileNameList 供外部传参,内部配置好文件格式与对应的样式。

核心在于Map、正则匹配、样式绑定。

vue

<template>
  <div>
    <span class="fileTag" v-for="fileName in fileNameList" :key="fileName" :style="getStyle(fileName)">
      {{ getEndStr(fileName) }}
    </span>
  </div>
</template>

js

const arr = [
  ["txt", { background: '#c79081' }],
  ["doc", { background: '#48c6ef' }],
  ["docx", { background: '#6f86d6' }],
  ["xslx", { background: '#accbee' }],
  ["pdf", { background: '#89f7fe' }],
  ["pkg", { background: '#f9f586' }],
  ["apk", { background: '#9890e3' }],
  ["svg", { background: '#d558c8' }],
  ["png", { background: '#f83600' }],
  ["gif", { background: '#9795f0' }],
  ["jpg", { background: '#fbc8d4' }],
  ["jpeg", { background: '#97d9e1' }]
]
export default {
  name: "FileTag",
  props: ['fileNameList'],
  data() {
    return {
      fileMap: new Map(arr)
    }
  },
  methods: {
    /** 获取文件类型 */
    getEndStr(fileName) {
      // 匹配文件名最后一个.后的字段
      return fileName.match(/[^.]+$/)[0];
    },
    
     /** 匹配文件样式 */
    getStyle(fileName) {
      let endStr = this.getEndStr(fileName)
      return this.fileMap.get(endStr) || { background: '#6e45e2' }

    }
  }
}

css

.fileTag {
  margin: 5px;
  padding: 4px 8px;
  color: #fff;
  border-radius: 5px;
  font-size: 14px;
  font-weight: bold;
}

Demo

接下来就是演示的环节了。

数据定义

 demo_fileNameList: ['dasdsa.xslx','dasds.pdf','fsdnk.jpg','dasda.txt','dasda.png','dassd.gif','asdda.unknow']

组件调用传参数

<file-tag :fileNameList="demo_fileNameList"></file-tag>

实现效果

通过Map实现Tag

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值