要诚恳,要坦然,要慷慨,要宽容,要有平常心
前言
在我们的平时开发过程中,为了高效的提示开发效率和缩短开发的时间,这时我们会想到使用一些周边的插件,今天小编整理了一下自己在开发过程中使用的插件,不仅是对知识的梳理,希望能帮助正在迷茫或者正在使用这些插件的你,让我们一起进步。Lockr
Lockr:本地存储 localStorage 的最小API,是一个非常轻量级的,宗旨是帮助你轻松使用localStorage,让使用本地存储保存对象、数组、数字、字符串省略很多步骤。
1 如何安装Lockr
如果你在使用终端:
npm i lockr --save 或者 cnpm i lockr -S 或者 yarn add lockr
或者你可以使用cdn
2 用法
设置一个前缀,该前缀会被追加到每一个键的字符串前面
Lockr.prefix - String
Lockr.prefix = 'lockr';Lockr.set('username', 'clown'); // Saved as stringlocalStorage.getItem('username');> nulllocalStorage.getItem('lockr_username');> {"data":'clown'}
2.设置,获取,删除,追加键值对
Lockr.set - 参数: [ key, value ] {String, Number, Array or Object} --> 设置一个指定的值,可以是任意类型Lockr.get - 参数: [ key or hash_key, default value ] --> 通过给定的键返回被保存的值,如果指定的键是null或undefined则会返回一个默认值Lockr.rm - 参数: [ key ] {String}--> 完全删除指定的键值对Lockr.sadd - 参数[ key, value ]{String, Number, Array or Object}--> 追加一个值在之前的基础上面(类似于 push() 方法)Lockr.getAll()--> 获取本地存储中所有的键值对Lockr.flush()-->清空本地存储 即localStorage.length==0
github:https://github.com/tsironis/lockr
axios
axios基于浏览器和node.js的基于Promise的HTTP客户端1 如何安装axios如果你使用的是终端
npm install axios -S 或者 cnpm install axios -S 或者 yarn add axios
使用cdn
2 用法1.创建一个实例 axios.create([config])
var instance = axios.create({ baseURL: 'https://www.clown.com/api',timeout: 1000, headers: {'X-Custom-Header': 'clown'}});
2.axios提供了一下请求方法
axios.request(config)axios.delete(url[, config])axios.head(url[, config])axios.post(url[, data[, config]])axios.put(url[, data[, config]])axios.patch(url[, data[, config]])
注意:在使用别名方法时,不需要在配置中指定'url'、'method'和'data'属性
3.以下是request请求方法中config的参数:
{ // `url` 是用于请求的服务器URL url: '/user', // `method` 是在发出请求时使用的请求方法 method: 'get', // default // `baseURL` 除非url是绝对的,否则将预先对url进行预处理。 //设置baseURL以传递相对url是很方便的。 // 对该实例的方法。 baseURL: 'https://some-domain.com/api/', // `transformRequest` allows changes to the request data before it is sent to the server // This is only applicable for request methods 'PUT', 'POST', and 'PATCH' // The last function in the array must return a string, an ArrayBuffer, or a Stream transformRequest: [function (data) { // Do whatever you want to transform the data return data; }], // `transformResponse` allows changes to the response data to be made before // it is passed to then/catch transformResponse: [function (data) { // Do whatever you want to transform the data return data; }], // `headers` are custom headers to be sent headers: {'X-Requested-With': 'XMLHttpRequest'}, // `params` are the URL parameters to be sent with the request // Must be a plain object or a URLSearchParams object params: { ID: 12345 }, // `paramsSerializer` is an optional function in charge of serializing `params` // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/) paramsSerializer: function(params) { return Qs.stringify(params, {arrayFormat: 'brackets'}) }, // `data` is the data to be sent as the request body // Only applicable for request methods 'PUT', 'POST', and 'PATCH' // When no `transformRequest` is set, must be of one of the following types: // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams // - Browser only: FormData, File, Blob // - Node only: Stream data: { firstName: 'Fred' }, // `timeout` specifies the number of milliseconds before the request times out. // If the request takes longer than `timeout`, the request will be aborted. timeout: 1000, // `withCredentials` indicates whether or not cross-site Access-Control requests // should be made using credentials withCredentials: false, // default // `adapter` allows custom handling of requests which makes testing easier. // Return a promise and supply a valid response (see [response docs](#response-api)). adapter: function (config) { /* ... */ }, // `auth` indicates that HTTP Basic auth should be used, and supplies credentials. // This will set an `Authorization` header, overwriting any existing // `Authorization` custom headers you have set using `headers`. auth: { username: 'janedoe', password: 's00pers3cret' }, // `responseType` indicates the type of data that the server will respond with // options are 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream' responseType: 'json', // default // `xsrfCookieName` is the name of the cookie to use as a value for xsrf token xsrfCookieName: 'XSRF-TOKEN', // default // `xsrfHeaderName` is the name of the http header that carries the xsrf token value xsrfHeaderName: 'X-XSRF-TOKEN', // default // `onUploadProgress` allows handling of progress events for uploads onUploadProgress: function (progressEvent) { // Do whatever you want with the native progress event }, // `onDownloadProgress` allows handling of progress events for downloads onDownloadProgress: function (progressEvent) { // Do whatever you want with the native progress event }, // `maxContentLength` defines the max size of the http response content allowed maxContentLength: 2000, // `validateStatus` defines whether to resolve or reject the promise for a given // HTTP response status code. If `validateStatus` returns `true` (or is set to `null` // or `undefined`), the promise will be resolved; otherwise, the promise will be // rejected. validateStatus: function (status) { return status >= 200 && status < 300; // default }, // `maxRedirects` defines the maximum number of redirects to follow in node.js. // If set to 0, no redirects will be followed. maxRedirects: 5, // default // `httpAgent` and `httpsAgent` define a custom agent to be used when performing http // and https requests, respectively, in node.js. This allows to configure options like // `keepAlive` that are not enabled by default. httpAgent: new http.Agent({ keepAlive: true }), httpsAgent: new https.Agent({ keepAlive: true }), // 'proxy' defines the hostname and port of the proxy server // `auth` indicates that HTTP Basic auth should be used to connect to the proxy, and supplies credentials. // This will set an `Proxy-Authorization` header, overwriting any existing `Proxy-Authorization` custom headers you have set using `headers`. proxy: { host: '127.0.0.1', port: 9000, auth: : { username: 'mikeymike', password: 'rapunz3l' } }, // `cancelToken` specifies a cancel token that can be used to cancel the request // (see Cancellation section below for details) cancelToken: new CancelToken(function (cancel) { })}
4.如果需求需要处理一些并发请求可以使用如下方法:
axios.all(iterable)axios.spread(callback)
5.在开发过程中我们还需要对一些请求头和响应体做一些特殊处理我们需要使用到拦截器Interceptors
// 添加请求拦截器axios.interceptors.request.use(function (config) { // Do something before request is sent return config; }, function (error) { // Do something with request error return Promise.reject(error); });// 添加响应拦截器axios.interceptors.response.use(function (response) { // Do something with response data return response; }, function (error) { // Do something with response error return Promise.reject(error); });
github:https://github.com/axios/axios 具体如果使用详见下一篇文章关于项目中的例子
lodash
lodash是一个一致性、模块化、高性能的Javascript实用工具库官网地址:https://www.lodashjs.com/
1 如何安装lodash
如果你使用的终端
$ npm i --save lodash 或者cnpm i lodash -S 或者yarn add loadsh
2 用法
其中包含了 array、number、objects、string 的许多开箱即用的方法和函数使得js变得简单
import _ form 'loadsh';_.debounce() //防抖函数_.isEmpty() //判断是否为空
Moment
moment是一个轻量级的JavaScript date库,用于解析、验证、操作和格式化日期。http://momentjs.cn/1 如何安装moment
使用终端输入
$ npm i --save moment或者cnpm i moment-S 或者yarn add moment
2 用法
设置语言
moment.locale("zh-cn");
格式化时间格式
moment().format('YYYY-MM-DD hh:mm:ss ');
3 在vue中如何减小moment包的大小我们知道在生产环境中包的大小会影响我们页面的加载速度,以及响应时间,我们在开发过程中要尽量减小包的体积,去掉没有用到的代码。这个时候我们就需要使用webpack了。
const webpack = require('webpack')module.exports = { chainWebpack: config => {// 忽略/moment/locale下的所有文件 config .plugin('ignore') .use(new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/)) }}
但是这个时候会有新的问题出现了,我们使用的中文也不会显示了,不要着急,小编带你做如下设置
import moment from 'moment'//手动引入所需要的语言包import 'moment/locale/zh-cn';// 指定使用的语言moment.locale('zh-cn');
最后,推荐在开发过程中使用day.js代替moment。day.js具有和moment相同的api,并且更加轻量级
NProgress
Nprogress是一个浏览器进度条的插件,可以使页面看起来很高大上,逼格瞬间提升1 如何安装NProgress如果使用终端
$ npm i --save nprogress或者cnpm i nprogress-S 或者yarn add nprogress
当然也可以使用cdn
2 用法这里是小编在vue项目简单的配置:
import router from './index'import NProgress from 'nprogress';import 'nprogress/nprogress.css';// 配置NProgress进度条选项 —— 动画效果NProgress.configure({ ease: 'linear', speed: 1000, showSpinner: false, minimum: 0.1 })router.beforeEach((to, from, next) => { //开始进度条 NProgress.start(); next();})//全局后置钩子router.afterEach((to, from) => {//NProgress结束进度条 NProgress.done()}
❤️爱心三连击
1.看到这里了就点个在看支持下吧,你的「在看」是我创作的动力。
2.关注公众号
猴哥说前端
,「一起玩转前端」!
3.扫码加我微信备注【加群】,拉你进技术交流群一起玩转前端。
“在看转发”是最大的支持