Vue 常用库

JS

file-saver 保存文件到硬盘

npm install file-saver
import { saveAs } from 'file-saver';
FileSaver saveAs(Blob/File/Url, optional DOMString filename, optional Object { autoBom })

{ autoBom: true }时 FileSaver.js 将自动提供 Unicode 文本编码提示(字节顺序标记)。Blob 类型设置为charset=utf-8的情况下才能执行此操作。

  • 示例
//blob
var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
saveAs(blob, "hello world.txt");
//url
saveAs("https://httpbin.org/image", "image.jpg");
//file
var file = new File(["Hello, world!"], "hello world.txt", {type: "text/plain;charset=utf-8"});
saveAs(file);

jszip 文件压缩

npm install jszip
import JSZip from "jszip";
  • 示例
var zip = new JSZip();
zip.file("Hello.txt", "Hello World\n");//压缩文件中添加文件Hello.txt
var img = zip.folder("images");//压缩文件中添加文件夹images
img.file("smile.gif", imgData, {base64: true});//文件夹images中添加文件smile.gif imgData类型为base64
img.file("Hello.txt", "Hello World\n");//文件夹images添加文件Hello.txt
img.remove("Hello.txt");//移除文件夹images中添加的文件Hello.txt
//zip.remove("images/Hello.txt");//效果同上
zip.generateAsync({type:"blob"})//生成压缩文件 类型为blob
.then(function(content) {
    saveAs(content, "example.zip");//见file-saver
});

var zip = new JSZip();
zip.loadAsync(content)//读取压缩包内容
.then(function(zip) {
    zip.file("hello.txt").async("string").then(res => {//读取压缩包中的hello.txt
      res//Hello World\n
    });
    zip.file("images/smile.gif").async("blob").then(res => {//读取压缩包中的images/smile.gif
      res//smile.gif的blob
    });
});

js-cookie cookie处理

npm install js-cookie
import Cookies from 'js-cookie'
  • 示例
Cookies.set('name', 'value')//添加一个cookie 关闭页面后清空
//等同于window.document.cookie="name=value;"
Cookies.get('name')//value 获取cookie值
Cookies.get()//{ name: 'value' } 获取全部cookie
Cookies.remove('name')//删除cookie

Cookies.set('name', 'value', { expires: 7 })//添加一个7天有效期的cookie
Cookies.set('name', 'value', {  path: '' })//添加一个当前页面可用的cookie
Cookies.get('name') // value 获取cookie值
Cookies.remove('name',  {  path: '' })//删除当前页面的cookie

Cookies.set('name', 'value1', {  domain: 'xxx.xxx.com' })//添加一个xxx.xxx.com域可用的cookie
Cookies.get('name',  {  domain: 'xxx.xxx.com' })//value1 获取该域的cookie值
Cookies.remove('name',  {  domain: 'xxx.xxx.com' })//删除该域的cookie

Cookies.set('name', 'value', { secure: true })//指示 Cookie 传输是否需要安全协议 https
Cookies.set('name', 'value', { sameSite: 'strict' })//允许浏览器是否在发送跨站点请求的同时发送 Cookie。
const api = Cookies.withAttributes({ path: '/', domain: '.example.com' })//给cookie设置默认的域和路径

crypto-js 加密

npm install crypto-js
import CryptoJS from 'crypto-js'
  • 示例
var hash = CryptoJS.MD5("Message");//md5加密
var hash = CryptoJS.SHA256("Message");//sha256加密

var encrypted = CryptoJS.AES.encrypt("Message", "Secret Passphrase");//aes加密
var decrypted = CryptoJS.AES.decrypt(encrypted, "Secret Passphrase");//aes解密

详见crypto-js

moment 日期处理库

npm install moment
import moment from "moment";
  • 示例
var now = moment();//获取当前日期的moment
now.format("yyyy-MM-DD HH:mm:ss SSS");//解析为字符串2022-01-01 11:11:11 111
now.add(7, 'days');//日期增加7天
now.format("yyyy-MM-DD HH:mm:ss SSS");//解析为字符串2022-01-08 11:11:11 111

详见Moment.js

clipboard 将内容放入剪切板

npm install clipboard
import ClipboardJS from 'clipboard';
  • 示例
let clipboard = new ClipboardJS('.btn');
//clipboard.destroy();//销毁实例

//点击按钮复制输入框的内容123



//点击按钮剪切输入框的内容123



//点击按钮复制123


//用js实现功能


new ClipboardJS('.btn', {
    target: function(trigger) {
        return trigger.nextElementSibling;//复制同胞元素(即input)的内容
    }
});


new ClipboardJS('.btn', {
    text: function(trigger) {
        return "123",//复制123
    }
});

详见clipboard.js

axios 获取服务端数据

npm install axios
import axios from 'axios';
  • 示例
//下载图片
axios({
  method:'get',
  url:'/api/getPicture',
  headers: {Authorization: "1234567890"},
  params: {
    name: "zhangsan"
  },
  responseType:'blob'
}).then(res => {
  FileSaver.saveAs(res.data, "zhangsan.jpg");
})
//保存图片
axios({
  method:'post',
  url:'/api/savePicture',
  headers: {Authorization: "1234567890"},
  data: {
    name: "zhangsan",
    blob: new Blob()
  },
}).then(res => {
    
})
// 并发
axios.all([axios.get("/api/getPicture?name=zhangsan"), axios.get("/api/getPicture?name=lisi")])
.then(axios.spread(function (acct, perms) {
    // 两个请求现在都执行完成
}))

详见axios

mockjs 拦截网络请求生成虚假数据

npm install mockjs
import Mock from 'mockjs';
  • 示例
Random.date()//生成日期占位符
Random.time()//生成时间占位符
Mock.mock("/api/user", "POST", {
    'list|1-10': [{//生成一个数组list 有1-10个对象
        'name': "zhangsan",//生成一个属性name 值为zhangsan
        'adress|3': "cd",//生成一个属性adress 值为cdcdcd
        'id|+1': 1,//生成一个属性id 值为自增数字1 2 3 4
        'age|10-30': 1//生成一个属性age 值为10-30中的整数
        'money|100-1000.0-2':1,//生成一个属性money,它是浮点数,整数在100-1000之中,小数保留0-2位,如555.1
        'birthday': "@date @time",//生成属性birthday 由占位符@date @time组成,即2000-01-01 12:00:00
    }]
})

axios.post('/api/user').then(res => {
      res
      //[{name: "zhangsan", adress: "cdcdcd", id: 1, age: 20, money: 333.20, birthday: "2020-11-11 11:11:11"}]
})

详见Mock

viewerjs 图片浏览器

npm install viewerjs
import Viewer from 'viewerjs';
new Viewer(element[, options])
  • 示例
//显示一张图片
Picture

const viewer = new Viewer(document.getElementById('image'), {
    //配置
})
//当点击图片后则会显示该图片浏览器 或者手动调用viewer.show()

//显示多张图片
const viewer = new Viewer(document.getElementById('images'), { }) //当点击图片后则会显示该图片浏览器 或者手动调用viewer. view(2) 数字为显示第几张图片

详见Viewer.js

xlsx 表格处理

npm install xlsx
import XLSX from 'xlsx'
  • 示例
// 导入xlsx
        // 创建input file
        let input = document.createElement('input')
        input.setAttribute('id', 'fileInput')
        input.setAttribute('type', 'file')
        input.setAttribute('accept', '.xlsx,.xls')//只能选择xlsx xls
        input.setAttribute("style", 'visibility:hidden')//隐藏元素
        document.body.appendChild(input)//添加到body上
        // 监听选择事件
        input.addEventListener('change', val => {
            let file = val.target.files[0] //取选择的第一个文件
            if (file) {
                let reader = new FileReader()
                reader.onload = function(e) {
                    // 文件读取完成
                    // 将文件转换为workbook
                    let wb = XLSX.read(e.target.result, {
                        type: "binary"
                    })
                    let sheetName = wb.SheetNames[0]
                    // xlsx数据转换为[{title1: "value1",title2: "value2"}]
                    let json = XLSX.utils.sheet_to_json(wb.Sheets[sheetName])
                    //移除元素
                    document.body.removeChild(input)
                }
                // 读取文件
                reader.readAsBinaryString(file)
            }
        })
        //触发点击事件弹出文件选择
        input.click()

//导出xlsx
        // 创建一个工作薄对象
        let wb = XLSX.utils.book_new()
        // 将json数据转换为工作表 datas [{title1: "value1", title2: "value2"}]
        let ws = XLSX.utils.json_to_sheet(datas, {
            header: ["title1", "title2"]//表头标题
        })
        // 工作薄中添加一个表sheet 表的内容为ws
        let sheetName = "sheet"
        wb.SheetNames.push(sheetName)
        wb.Sheets[sheetName] = ws
        //导出工作薄
        XLSX.writeFile(wb, "test.xlsx")

详见 xlsx 与 xlsx低版本中文文档

qs 字符串解析器

npm install qs
import qs from 'qs';
  • 示例
let a = "?title=hello&id=123456&name=cd/zhangsan"
let b = qs.parse(a, { ignoreQueryPrefix: true })//{title: 'hello', id: '123456', name: 'cd/zhangsan'} 
//ignoreQueryPrefix的作用是在解析前去掉前面的?
let c = qs.stringify(b)//'title=hello&id=123456&name=cd%2Fzhangsan'
let d = qs.stringify(b, { addQueryPrefix: true, encode: false})//'?title=hello&id=123456&name=cd/zhangsan'
//addQueryPrefix的作用是在字符串前添加? encode默认为true,作用是将字符串 URI 编码 /会被编码为%2F

详见qs

UI

vuescroll 自定义滚动条

npm install vuescroll

import vuescroll from 'vuescroll';
export default {
    components: {
      vuescroll
    }
};
  • 示例



详见Vuescroll.js

vue-qrcode 二维码 vue-barcode 条形码

npm install @chenfengyuan/vue-qrcode
import VueQrcode from '@chenfengyuan/vue-qrcode';

npm install  @chenfengyuan/vue-barcode
import VueBarcode from '@chenfengyuan/vue-barcode';
  • 示例



详见vue-qrcode vue-barcode

nprogress 进度条

npm install nprogress
import NProgress from "nprogress"
  • 示例
NProgress.configure({ showSpinner: true, parent: '#aaa' });//配置 
//showSpinner默认为true,界面右上角有一个圈圈在转 
//parent默认为document.body,即在整个界面上显示进度条 #aaa表示在id="aaa"的元素上显示进度条
NProgress.start()//开始走进度

NProgress.done()//进度完成

效果如下


详见nprogress

你可能感兴趣的:(Vue 常用库)