# common-plugin

> * 以下所说全局为VUE全局，不是window全局，需要在VUE实例中用this.调用。 * 安装依赖要用cnpm，不要用npm（下面有教程）

Latest version **1.0.33** (published 2021-11-10) · ISC license · 0 weekly downloads

## Install

```sh
npm install common-plugin
pnpm add common-plugin
yarn add common-plugin
bun add common-plugin
```

## Health

**Score 15/100 (F)** — status: abandoned.

Positive: no vulnerabilities.

Warnings: low downloads; no types; no esm support.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 1.0.33 |
| Published | 2021-11-10 |
| First published | 2020-06-17 |
| Weekly downloads | 0 |
| License | ISC |
| TypeScript types | none |
| Module format | CommonJS |
| Dependencies | 5 |
| Unpacked size | 699.6 KB |
| Known vulnerabilities | 0 (+28 in 3 direct dependencies) |
| Install scripts | no |
| Maintainers | cht111 |

## Links

- npm: https://www.npmjs.com/package/common-plugin
- npm.io page: https://npm.io/package/common-plugin

## Dependencies (5)

- [qs](https://npm.io/package/qs.md) ~6.9.1
- [vue](https://npm.io/package/vue.md) ^2.6.14
- [axios](https://npm.io/package/axios.md) ^0.21.1
- [js-base64](https://npm.io/package/js-base64.md) ^2.5.1
- [@types/js-base64](https://npm.io/package/@types/js-base64.md) ^2.3.1

## Recent versions

- 1.0.33 (latest) — 2021-11-10
- 1.0.32 — 2021-11-10
- 1.0.31 — 2021-11-10
- 1.0.30 — 2021-11-09
- 1.0.29 — 2021-03-23
- 1.0.28 — 2020-12-18
- 1.0.27 — 2020-12-17
- 1.0.26 — 2020-11-26
- 1.0.25 — 2020-11-10
- 1.0.24 — 2020-11-06
- 1.0.23 — 2020-11-05
- 1.0.22 — 2020-10-27
- 1.0.21 — 2020-10-23
- 1.0.20 — 2020-10-23
- 1.0.19 — 2020-10-22
- … 18 more at https://npm.io/package/common-plugin/versions

## README

# 说明
* 以下所说全局为VUE全局，不是window全局，需要在VUE实例中用this.调用。
* 安装依赖要用cnpm，不要用npm（下面有教程）

# 启动项目 
* 安装淘宝镜像: `npm install -g cnpm --registry=https://registry.npm.taobao.org` 该工具为全局工具，只需安装一次
* 安装依赖: `cnpm i ` 每个项目单独安装
* 运行: `npm run serve`

# 配置代理
* 配置文件路径：`src/commonPluginConfig/axios.js`
* 配置案例：
    ```javascript
      proxy: {
        '/foreign/': {
          target: 'http://www.test.cntytz.com',
          changeOrigin: true,
          ws: true,
          pathRewrite: {
            ['^' + '/foreign/']: '/foreign/'
          }
        }
      }
    ```
    加入该配置后，会自动捕获`/foreign/`路径，并且自动代理到`http://www.test.cntytz.com/foreign/`上。

# [elememtUI](https://element.eleme.cn/#/zh-CN/component/installation)
以下为优化后的elementUI说明文档。
## dialog
* 全局变量 
  * dialogVisible  
    ```javascript
      data () {
          return {
              dialogVisible: false
          }
      },
    ```
    该属性挂载在每一个vue页面实例上可以直接使用。初始化为false。
    例：
    ```html
    <el-dialog :visible.sync="dialogVisible">
    </el-dialog>
    ```
* 方法
  ```javascript
  methods: {
    clearDialogForm (ref) {
    
    }
  }
  ```
  该方法需要绑定在dialog上的before-close（dialog关闭前）方法使用：
  ```html
  <el-dialog :before-close="clearDialogForm($refs.form)"></el-dialog>
  ```
  该方法挂载在每个vue页面实例上并直接可用。接收一个可选的form对象参数，传递的话会清空指定的form表单内容，不传递的话会清空该vue页面上的所有form表单，并且关闭dialog

## loading
* 计算属性
  globalDataLoading
  ```javascript
  computed: {
      ...mapState({
          globalDataLoading: state => (state as any).globalDataLoading
      })
  }
  ```
  该属性挂载在每一个vue页面实例上可以直接使用。只要有任意一个请求未完成，该变量都为ture,所有请求都完成后会变成false。

  例：
  ```html
  <div v-loading="globalDataLoading">content</div>
  ```
  只要有ajax请求还未结束，该div都会有loading效果。

## 分页器
在elementUI的基础上封装了分页器，使其更加方便可用并且风格统一。
* 全局变量
  ```javascript
  data () {
    return {
      pageLimit: 10, //每页条数
      pageIndex: 1, //当前是第几页
      pageTotal: 0, //数据总量
      pageLimits: [10, 20, 50, 100],
      pageLayout: 'total,sizes,prev, pager,next,jumper'
    }
  }
  ```
  这五个变量是全局可用并且组件之间是独立的互不影响。
* ty-pagination组件
  ```html
  <ty-pagination
    @initDataFunc="initDataFunc"
    v-model="pageIndex"
    :total="pageTotal"
  ></ty-pagination>
  ```
  该组件需要双向绑定当前页码数（v-model）、传入数据总条数（total）、定义请求事件。该组件已经全局注册，不用再局部注册。initDataFunc事件会传递一个对象参数：
  ```javascript
  {
      pageLimit: 10,
      pageIndex: 1
  }
  ```
  * 方法
    * this.$refs.page.reload() 刷新数据

## message
* 方法

  对message封装，并且暴露全局可用方法：
  ```javascript
  this.msg({ message: 'error提示' })
  ```
  该方法接收的参数与message接收的参数相同，不同点有两个：
    * 消息提示默认类型为error
    * 同一个时间只能存在一个message实例，如果第一个未关闭第二个就弹出，会自动关闭第一个message实例。
* 样式
  
  优化了message弹框的风格样式

## messageBox
优化了ElementUI全局方法 $alert, $confirm 和 $prompt,合并三个参数为一个，并对应定义全局方法：alert、confirm、prompt（官方文档中的配置参数全部可用）。
```javascript
this.prompt({ message: '消息主体', title: '提示' }).then(result => {
  console.log(result)
})
this.confirm({ message: '消息主体', title: '提示' }).then(result => {
  console.log(result)
})
this.alert({ message: '消息主体', title: '提示' }).then(result => {
  console.log(result)
})
```
## 表单校验
* 自定义校验规则
  ```javascript
  rules: {
    pass: [
      { validator: validatePass, trigger: 'blur' }
    ]
  }
  ```
  该案例将会对pass字段进行自定义的`validatePass`校验
* 校验方法
  * elValidate.checkPhoneNumber
    ```javascript
    { validator: this.elValidate.checkPhoneNumber, trigger: 'change' } //校验电话号码
    ```
  * elValidate.checkIdCardNumber
    ```javascript
    { validator: this.elValidate.checkIdCardNumber, trigger: 'change' } //校验电话身份证
    ```
  * elValidate.checkSpechars
    ```javascript
    { validator: this.elValidate.checkSpechars, trigger: 'change' }//特殊符号校验
    ```
    
  * elValidate.checkUnifiedSocialCreditCode
    ```javascript
    { validator: this.elValidate.checkUnifiedSocialCreditCode, trigger: 'change' } //统一社会信用代码校验
    ```
    
# Vue相关方法（mixin）

* resetData()
  ```javascript
  this.resetData('dataList')
  ```
  初始化数据对象。暴露全局方法resetData，接收一个字符串，为data对象里的数据key值，该案例会将当前vue页面实例的data对象中的dataList数据设置为页面初始加载的状态。也可用来在关闭dialog时清空dialog里的数据对象。

# Vue相关方法（prototype）

# axios
对axios进行封装，自动化提示错误消息

## 请求方法
公共参数：
```javascript
{
  url: string;// 请求路径
  headers?: any;// 配置请求头;
  ignoreInterceptRes?: boolean; // 是否拦截非成功返回，默认拦截
  checkLogin?: boolean; // 是否检查登录，默认不检查
  ignoreToken?:boolean;  //是否忽略在header里传递token，默认传递
  cache?:boolean;  //是否缓存，默认不缓存
}
```
* GET方法
  ```javascript
  import { request } from 'common-plugin';
  request.$get({
    url:'/getData',
    data:{}
  })
  ```
* POST方法
    ```javascript
    import {request } from 'common-plugin'
    return request.$post({
      url:'/getData',
      data:{}
    })
    ```
    独有参数
    ```javascript
    {
      isForm?: boolean; // 是否表单提交，默认json提交
    }
    ```
*  PUT方法
    ```javascript
    import { request } from 'common-plugin';
    request.$put({
        url:'/put'
    })
    ```
* DELETE方法
    ```javascript
    import { request } from 'common-plugin';
    request.$delete({
        url:'/delete'
    })
    ```

## 返回数据格式
```javascript
{
  code: number,
  msg: string,
  data: any
}
```
若返回数据格式不正确，控制台会提示警告，并且会影响公共的请求错误处理

## 响应拦截
默认拦截所有返回非成功码的请求对应做以下处理：
* 提示
  
  默认会提示用户错误信息：
  ```javascript
  this.msg({message:res.msg})
  ```
  该提示可以通过请求配置中的 ignoreInterceptRes 参数配置是否弹出
* 拦截未登录（暂未确定确定的状态码）
  
  拦截到未登录的状态码时会提示未登录，提示框关闭后会跳转登录页面
  ```javascript
  Vue.prototype.msg({
    message: '检测到您还未登录，即将为您跳转到登录页面...',
    type: 'error',
    duration: 2000,
    onClose: () => {
      window.location.href = Vue.prototype.globalUrl.mall + '/logout.html'
    }
  })
  ```

# 工具包
定义全局可用工具包tyPlugin,将常用的方法封装。

* currencyFormat
  金额格式化 
  ```javascript
  this.tyPlugin.currencyFormat('1231312') // 1,231,312.00
  ```
* DelCurrencyFormat
  删除千位符 
  ```javascript
  this.tyPlugin.DelCurrencyFormat('1,231,312.00') // 1231312.00
  ```
* convertCurrency
  金额大写
  ```javascript
  this.tyPlugin.convertCurrency('1231312') // 壹佰贰拾叁万壹仟叁佰壹拾贰元整
  ```
* urlStringToObj
  URL字符串转化为对象
  ```javascript
  this.tyPlugin.urlStringToObj('localhost:8080/as?a=1&b=2') // {a: "1", b: "2"}
  ```
* objectToQueryString
  将对象转化成查询参数
  ```javascript
  this.tyPlugin.objectToQueryString({ a: 12, b: 3 }) // a=12&b=3
  ```
* escape
  字符串编码
  ```javascript
  this.tyPlugin.escape('http://localhost:8080/#/') // http%3A//localhost%3A8080/%23/
  ```
* unescape
  字符串解码
  ```javascript
  this.tyPlugin.unescape('http%3A//localhost%3A8080/%23/') // http://localhost:8080/#/
  ```
* midHide
  数据隐藏
  ```javascript
  this.tyPlugin.midHide('12345678901',3,3) // 123*****901
  ```
  该方法接收三个参数，第一个目标字符串为必填参数，第二个开头显示的字符数为选填，第三个末尾显示的字符数为选填，默认为首3尾4。
* getAllStyle
  获取元素的计算样式
  ```javascript
  this.tyPlugin.getAllStyle(dom) // CSSStyleDeclaration实例
  ```
* getDomSPInfo
  获取元素大小及其相对于视口的位置。
  ```javascript
  this.tyPlugin.getDomSPInfo(dom) // DOMRect实例
  ```
* setSessionStorage
  sessionstorage里面存数据
  ```javascript
  this.tyPlugin.setSessionStorage('userData',{:name:'john'}) 
  ```
  接收两个参数，第一个参数为key值，第二个参数为value值。
* getSessionStorage
  sessionstorage里面取数据
  ```javascript
  this.tyPlugin.getSessionStorage('userData') 
  ```
  接收一个参数，要获取的数据的key值
* debounce
  函数防抖，触发高频事件后n秒内函数只会执行一次，如果n秒内高频事件再次被触发，则重新计算时间
  ```javascript
  this.tyPlugin.debounce(Function,time) 
  ```
  接收两个参数，第一个为要执行的函数，第二个可选参数，为延时秒数，默认200ms
* jsonClone
  数据克隆
  ```javascript
  this.tyPlugin.jsonClone(data) 
  ```
  接收要克隆的数据，返回克隆后的数据
* getDayCount
  获取传入时间所在月有几天
  ```javascript
  this.tyPlugin.getDayCount(data) 
  ```
* initObj
  初始化对象参数
  ```javascript
  this.tyPlugin.initObj(target: any, val?: any) 
  ```
  接收两个参数，第一个为要修改的目标对象，第二个为对比参数，target要置为val的值。若不传第二个参数，默认置为''
* getDateArr
  获取时间数组
  ```javascript
  this.tyPlugin.getDateArr() 
  ```
  返回值：[YYYY,MM,DD]
* getDateObj
  获取时间对象
  ```javascript
  this.tyPlugin.getDateObj(str?: string | number) 
  ```
  返回值Date实例 参数默认为当前时间
* bankNumberFormat
  格式化银行卡账号
  ```javascript
  this.tyPlugin.bankNumberFormat(str) 
  ```
  返回由空格隔开的银行卡号码：1111 2222 3323 3432 2434
* dataListMerge
  数据合并
  ```javascript
  this.tyPlugin.dataListMerge(data1,data2,key) 
  ```
  根据key字段，合并data1和data2数组
* isDomInView
  动态监测DOM元素是否在当前视野中
  ```javascript
  this.tyPlugin.isDomInView(config: {
    dom: Element;
    change(data: { data: boolean }): void;
  })
  ```
  dom为要监测的dom元素，change为回调函数，参数为Boolean
* scrollDirection
  动态监测页面滚动的方向
  ```javascript
  this.tyPlugin.scrollDirection(data: {
      change: (data:
        {
          event: Event,
          direction: { X: number, Y: number }
        }) => void,
      config?: AddEventListenerOptions
  })
  ```
  change为回调函数，direction为方向，event为事件；config为事件的配置

* tyPlugin.validate
    
  `tyPlugin.validate`返回一个对象：包含以下校验方法：
  * tyPlugin.validate.checkIdCardNumber
    ```javascript
    this.tyPlugin.validate.checkIdCardNumber(str:string|number):boolean
    ```
    检测传入的身份证号码是否合法
  * tyPlugin.validate.checkPhoneNumber
    ```javascript
    this.tyPlugin.validate.checkPhoneNumber(str:string|number):boolean
    ```
    检测传入的手机号码是否合法
  * tyPlugin.validate.isFloatNumber
    ```javascript
    this.tyPlugin.validate.isFloatNumber(str:string|number):boolean
    ```
    小数数字校验
  * tyPlugin.validate.isIntNumber
    ```javascript
    this.tyPlugin.validate.isIntNumber(str:string|number):boolean
    ```
    整数数字校验
  * tyPlugin.validate.checkUnifiedSocialCreditCode
      ```javascript
      this.tyPlugin.validate.checkUnifiedSocialCreditCode(str:string):boolean
      ```
      统一社会信用代码校验
  * tyPlugin.validate.isNoSpechars
    ```javascript
    this.tyPlugin.validate.isNoSpechars(str:string):boolean
    ```
    特殊字符校验，包括以下字符：
    ```javascript
        const regEn = /[`~!@#$%^&*()_+<>?:"{},./;'[\]]/img
        const regCn = /[·！#￥（——）：；“”‘、，|《。》？、【】[\]]/img
    ```
* tyPlugin.equipment
    
  `tyPlugin.equipment`返回一个对象：包含以下校验方法：
  * tyPlugin.equipment.isIOS
    ```javascript
    this.tyPlugin.equipment.isIOS():boolean
    ```
    检测当前设备是否是ios
  * tyPlugin.equipment.isMobile
    ```javascript
    this.tyPlugin.equipment.isMobile():boolean
    ```
    检测当前设备是否是移动端
* tyPlugin.platform
    
  `tyPlugin.platform`返回一个对象：包含以下校验方法：
  * tyPlugin.platform.isWeChat
    ```javascript
    this.tyPlugin.platform.isWeChat():boolean
    ```
    检测当前平台是否是微信
 


# VUEX
* 注意
  * 不要改变src下边的store文件夹名和store文件夹下面的index.ts文件名！

* getStoreData
```javascript
this.getStoreData('userInfo')
```
获取vuex里的数据
* setStoreData
```javascript
this.setStoreData('userInfo',val)
```
设置vuex的数据

# filter 过滤器
主要用来格式化数据：
```html
<span>{{data|currencyFormat}}</span>
<input :value="data|currencyFormat">
```
span、input的内容显示为currencyFormat的返回值，参数为data。

现有方法如下：
* currencyFormat 
  金额格式化方法
* formatDate 
  日期格式化方法   YYYY-MM-DD
* midHide 
  隐藏中间内容：  131****7235
* convertCurrency 
  金额大写
* bankNumberFormat
  格式化银行卡账号
  返回由空格隔开的银行卡号码：1111 2222 3323 3432 2434

# directive 指令
* focus
```html
自动聚焦
<input v-focus/>
```
# vue-router
## 说明
* 系统内部的跳转，统一使用`<router-link>`组件

## 方法
* routeBack
```javascript
  this.routeBack() //返回上一页
```

* isNameInRouters
```javascript
  this.isNameInRouters(index:string):boolean //当前路由以及嵌套路由是否含有name为index的页面。
```

* isItemInRouterMeta
```javascript
  this.isItemInRouterMeta(index:string|array):boolean //当前路由以及嵌套路由的meta数据里是否包含index的数据,入参可以是字符串，也可以是字符串组成的数组。
```
* getParams
```javascript
  this.getParams():any //获取params数据，并且刷新页面不会丢失
```
* setQuery
```javascript
  this.setQuery(data):viod //设置query数据
```

## 页面跳转
* router-link
  ```html
    <router-link to="/foo">Go to Foo</router-link>
  ```
* 编程式导航
  ```javascript
  this.$router.push({
    path: '/index'
  })
  ```

## 路由传参
* query传参
  * router-link
    ```html
    <router-link :to="{path:'/financial',query:{index:0}}">融资超市</router-link>
    ```
  * 编程式
    ```javascript
    this.$router.push({
      path: '/index',
      query: {
        bankId: 12121
      }
    })
    ```

* params传参
  
  params传参页面手动刷新后会丢失！
  * router-link
    ```html
    <router-link :to="{ name: 'user', params: { userId: 123 }}">User</router-link>
    ```
  * 编程式
    ```javascript
    this.$router.push({
      name: 'index',
      params: {
        bankId: 12121
      }
    })
    ```

* 两种传参方式区别
query传参会在地址上显示，params传参不会
## 路由接收参数
* query
  ```javascript
  this.$route.query
  ```
* params
  ```javascript
  this.$route.params
  ```
# 组件
* wait-line
  ```html
   <wait-line></wait-line>
  ```
  有ajax请求的时候自动在组件顶部出现加载条

* ty-ad
  ```html
   <ty-ad></ty-ad>
  ```
  广告组件
  * attrs
  ```
  imgUrl:图片路径
  link:链接地址
  ```
# 注意事项
## Date
因为各个浏览器对时间字符串格式要求不同的原因，注意以下事项：
* 如果要将时间字符串转化为时间对象，要调用`tyPlugin.getDateObj(str)`来获取，不可直接`new Date(str)`;
* 如果要将时间戳转化为时间对象，那么入参必须为number类型。

---
_Source: https://npm.io/package/common-plugin · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
