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 文本編碼提示(字節(jié)順序標(biāo)記)。Blob 類型設(shè)置為charset=utf-8的情況下才能執(zhí)行此操作嗦锐。

  • 示例
//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)//讀取壓縮包內(nèi)容
.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 關(guān)閉頁面后清空
//等同于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: '' })//添加一個當(dāng)前頁面可用的cookie
Cookies.get('name') // value 獲取cookie值
Cookies.remove('name'寄锐,  {  path: '' })//刪除當(dāng)前頁面的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 傳輸是否需要安全協(xié)議 https
Cookies.set('name', 'value', { sameSite: 'strict' })//允許瀏覽器是否在發(fā)送跨站點請求的同時發(fā)送 Cookie。
const api = Cookies.withAttributes({ path: '/', domain: '.example.com' })//給cookie設(shè)置默認(rèn)的域和路徑

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();//獲取當(dāng)前日期的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 將內(nèi)容放入剪切板

npm install clipboard
import ClipboardJS from 'clipboard';
  • 示例
let clipboard = new ClipboardJS('.btn');
//clipboard.destroy();//銷毀實例

//點擊按鈕復(fù)制輸入框的內(nèi)容123
<input id="foo" value="123">
<button class="btn" data-clipboard-target="#foo">
    復(fù)制
</button>

//點擊按鈕剪切輸入框的內(nèi)容123
<input id="foo" value="123">
<button class="btn" data-clipboard-target="#foo"  data-clipboard-action="cut">
    剪切
</button>

//點擊按鈕復(fù)制123
<button class="btn" data-clipboard-text="123">
  復(fù)制
</button>

//用js實現(xiàn)功能
<input id="foo" value="123">
<button class="btn">
  復(fù)制
</button>
new ClipboardJS('.btn', {
    target: function(trigger) {
        return trigger.nextElementSibling;//復(fù)制同胞元素(即input)的內(nèi)容
    }
});

<button class="btn">
  復(fù)制
</button>
new ClipboardJS('.btn', {
    text: function(trigger) {
        return "123",//復(fù)制123
    }
});

詳見clipboard.js

axios 獲取服務(wù)端數(shù)據(jù)

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 => {
    
})
// 并發(fā)
axios.all([axios.get("/api/getPicture?name=zhangsan"), axios.get("/api/getPicture?name=lisi")])
.then(axios.spread(function (acct, perms) {
    // 兩個請求現(xiàn)在都執(zhí)行完成
}))

詳見axios

mockjs 攔截網(wǎng)絡(luò)請求生成虛假數(shù)據(jù)

npm install mockjs
import Mock from 'mockjs';
  • 示例
Random.date()//生成日期占位符
Random.time()//生成時間占位符
Mock.mock("/api/user", "POST", {
    'list|1-10': [{//生成一個數(shù)組list 有1-10個對象
        'name': "zhangsan",//生成一個屬性name 值為zhangsan
        'adress|3': "cd",//生成一個屬性adress 值為cdcdcd
        'id|+1': 1,//生成一個屬性id 值為自增數(shù)字1 2 3 4
        'age|10-30': 1//生成一個屬性age 值為10-30中的整數(shù)
        'money|100-1000.0-2':1,//生成一個屬性money,它是浮點數(shù),整數(shù)在100-1000之中谤祖,小數(shù)保留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])
  • 示例
//顯示一張圖片
<img id="image" src="picture.jpg" alt="Picture">

const viewer = new Viewer(document.getElementById('image'), {
    //配置
})
//當(dāng)點擊圖片后則會顯示該圖片瀏覽器 或者手動調(diào)用viewer.show()

//顯示多張圖片
<div id="images">
    <img src="picture1.jpg">
    <img src="picture2.jpg">
    <img src="picture3.jpg">
</ul>
const viewer = new Viewer(document.getElementById('images'), {
})
//當(dāng)點擊圖片后則會顯示該圖片瀏覽器 或者手動調(diào)用viewer. view(2) 數(shù)字為顯示第幾張圖片

詳見Viewer.js

xlsx 表格處理

npm install xlsx
import XLSX from 'xlsx'
  • 示例
// 導(dǎo)入xlsx
        // 創(chuàng)建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上
        // 監(jiān)聽選擇事件
        input.addEventListener('change', val => {
            let file = val.target.files[0] //取選擇的第一個文件
            if (file) {
                let reader = new FileReader()
                reader.onload = function(e) {
                    // 文件讀取完成
                    // 將文件轉(zhuǎn)換為workbook
                    let wb = XLSX.read(e.target.result, {
                        type: "binary"
                    })
                    let sheetName = wb.SheetNames[0]
                    // xlsx數(shù)據(jù)轉(zhuǎn)換為[{title1: "value1",title2: "value2"}]
                    let json = XLSX.utils.sheet_to_json(wb.Sheets[sheetName])
                    //移除元素
                    document.body.removeChild(input)
                }
                // 讀取文件
                reader.readAsBinaryString(file)
            }
        })
        //觸發(fā)點擊事件彈出文件選擇
        input.click()

//導(dǎo)出xlsx
        // 創(chuàng)建一個工作薄對象
        let wb = XLSX.utils.book_new()
        // 將json數(shù)據(jù)轉(zhuǎn)換為工作表 datas [{title1: "value1", title2: "value2"}]
        let ws = XLSX.utils.json_to_sheet(datas, {
            header: ["title1", "title2"]//表頭標(biāo)題
        })
        // 工作薄中添加一個表sheet 表的內(nèi)容為ws
        let sheetName = "sheet"
        wb.SheetNames.push(sheetName)
        wb.Sheets[sheetName] = ws
        //導(dǎo)出工作薄
        XLSX.writeFile(wb, "test.xlsx")

詳見 xlsxxlsx低版本中文文檔

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默認(rèn)為true粥喜,作用是將字符串 URI 編碼 /會被編碼為%2F

詳見qs

UI

vuescroll 自定義滾動條

npm install vuescroll

import vuescroll from 'vuescroll';
export default {
    components: {
      vuescroll
    }
};
  • 示例
<template>
    <div>
        <vue-scroll :ops="ops" style="height: 500px;">
            <div style="height: 800px;"></div>
        </vue-scroll>
    </div>
</template>

<script>
    import vuescroll from 'vuescroll'

    export default {
        components: {
            vuescroll
        },
        data: function() {
            return {
                ops: {
                    vuescroll: {}, //基本設(shè)置
                    scrollPanel: {}, //滾動設(shè)置
                    rail: {}, //滾動條軌道設(shè)置
                    bar: {}, //滾動條設(shè)置
                    scrollButton: {}, //滾動條上下或左右箭頭按鈕的設(shè)置
                }
            }
        }
    }
</script>

詳見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';
  • 示例
<template>
    <div>
        <vue-qrcode value="Hello, World!" :options="options"></vue-qrcode>
        <vue-barcode  value="Hello, World!" :options="options"></vue-barcode>
    </div>
</template>

<script>
    import VueQrcode from '@chenfengyuan/vue-qrcode'
    import VueBarcode from '@chenfengyuan/vue-barcode';

    export default {
        components: {
            VueQrcode,
            VueBarcode
        },
        data: function() {
            return {
                options: {
                    
                }
            }
        }
    }
</script>

詳見vue-qrcode vue-barcode

nprogress 進度條

npm install nprogress
import NProgress from "nprogress"
  • 示例
NProgress.configure({ showSpinner: true, parent: '#aaa' });//配置 
//showSpinner默認(rèn)為true,界面右上角有一個圈圈在轉(zhuǎn) 
//parent默認(rèn)為document.body橘券,即在整個界面上顯示進度條 #aaa表示在id="aaa"的元素上顯示進度條
NProgress.start()//開始走進度

NProgress.done()//進度完成

效果如下


詳見nprogress

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末额湘,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子旁舰,更是在濱河造成了極大的恐慌锋华,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,651評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件箭窜,死亡現(xiàn)場離奇詭異毯焕,居然都是意外死亡,警方通過查閱死者的電腦和手機磺樱,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,468評論 3 392
  • 文/潘曉璐 我一進店門纳猫,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人竹捉,你說我怎么就攤上這事芜辕。” “怎么了块差?”我有些...
    開封第一講書人閱讀 162,931評論 0 353
  • 文/不壞的土叔 我叫張陵侵续,是天一觀的道長。 經(jīng)常有香客問我憨闰,道長状蜗,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,218評論 1 292
  • 正文 為了忘掉前任鹉动,我火速辦了婚禮诗舰,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘训裆。我一直安慰自己眶根,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,234評論 6 388
  • 文/花漫 我一把揭開白布边琉。 她就那樣靜靜地躺著属百,像睡著了一般。 火紅的嫁衣襯著肌膚如雪变姨。 梳的紋絲不亂的頭發(fā)上族扰,一...
    開封第一講書人閱讀 51,198評論 1 299
  • 那天,我揣著相機與錄音,去河邊找鬼渔呵。 笑死怒竿,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的扩氢。 我是一名探鬼主播耕驰,決...
    沈念sama閱讀 40,084評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼录豺!你這毒婦竟也來了朦肘?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,926評論 0 274
  • 序言:老撾萬榮一對情侶失蹤双饥,失蹤者是張志新(化名)和其女友劉穎媒抠,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體咏花,經(jīng)...
    沈念sama閱讀 45,341評論 1 311
  • 正文 獨居荒郊野嶺守林人離奇死亡趴生,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,563評論 2 333
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了昏翰。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片苍匆。...
    茶點故事閱讀 39,731評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖矩父,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情排霉,我是刑警寧澤窍株,帶...
    沈念sama閱讀 35,430評論 5 343
  • 正文 年R本政府宣布,位于F島的核電站攻柠,受9級特大地震影響球订,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜瑰钮,卻給世界環(huán)境...
    茶點故事閱讀 41,036評論 3 326
  • 文/蒙蒙 一冒滩、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧浪谴,春花似錦开睡、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,676評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至凶杖,卻和暖如春胁艰,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,829評論 1 269
  • 我被黑心中介騙來泰國打工腾么, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留奈梳,地道東北人。 一個月前我還...
    沈念sama閱讀 47,743評論 2 368
  • 正文 我出身青樓解虱,卻偏偏與公主長得像攘须,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子饭寺,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,629評論 2 354

推薦閱讀更多精彩內(nèi)容