1.0.33 • Published 2 years ago

common-plugin v1.0.33

Weekly downloads
-
License
ISC
Repository
-
Last release
2 years ago

说明

  • 以下所说全局为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
  • 配置案例:
      proxy: {
        '/foreign/': {
          target: 'http://www.test.cntytz.com',
          changeOrigin: true,
          ws: true,
          pathRewrite: {
            ['^' + '/foreign/']: '/foreign/'
          }
        }
      }
    加入该配置后,会自动捕获/foreign/路径,并且自动代理到http://www.test.cntytz.com/foreign/上。

elememtUI

以下为优化后的elementUI说明文档。

dialog

  • 全局变量
    • dialogVisible
        data () {
            return {
                dialogVisible: false
            }
        },
      该属性挂载在每一个vue页面实例上可以直接使用。初始化为false。 例:
      <el-dialog :visible.sync="dialogVisible">
      </el-dialog>
  • 方法
    methods: {
      clearDialogForm (ref) {
      
      }
    }
    该方法需要绑定在dialog上的before-close(dialog关闭前)方法使用:
    <el-dialog :before-close="clearDialogForm($refs.form)"></el-dialog>
    该方法挂载在每个vue页面实例上并直接可用。接收一个可选的form对象参数,传递的话会清空指定的form表单内容,不传递的话会清空该vue页面上的所有form表单,并且关闭dialog

loading

  • 计算属性 globalDataLoading

    computed: {
        ...mapState({
            globalDataLoading: state => (state as any).globalDataLoading
        })
    }

    该属性挂载在每一个vue页面实例上可以直接使用。只要有任意一个请求未完成,该变量都为ture,所有请求都完成后会变成false。

    例:

    <div v-loading="globalDataLoading">content</div>

    只要有ajax请求还未结束,该div都会有loading效果。

分页器

在elementUI的基础上封装了分页器,使其更加方便可用并且风格统一。

  • 全局变量
    data () {
      return {
        pageLimit: 10, //每页条数
        pageIndex: 1, //当前是第几页
        pageTotal: 0, //数据总量
        pageLimits: [10, 20, 50, 100],
        pageLayout: 'total,sizes,prev, pager,next,jumper'
      }
    }
    这五个变量是全局可用并且组件之间是独立的互不影响。
  • ty-pagination组件
    <ty-pagination
      @initDataFunc="initDataFunc"
      v-model="pageIndex"
      :total="pageTotal"
    ></ty-pagination>
    该组件需要双向绑定当前页码数(v-model)、传入数据总条数(total)、定义请求事件。该组件已经全局注册,不用再局部注册。initDataFunc事件会传递一个对象参数:
    {
        pageLimit: 10,
        pageIndex: 1
    }
    • 方法
      • this.$refs.page.reload() 刷新数据

message

  • 方法

    对message封装,并且暴露全局可用方法:

    this.msg({ message: 'error提示' })

    该方法接收的参数与message接收的参数相同,不同点有两个:

    • 消息提示默认类型为error
    • 同一个时间只能存在一个message实例,如果第一个未关闭第二个就弹出,会自动关闭第一个message实例。
  • 样式

    优化了message弹框的风格样式

messageBox

优化了ElementUI全局方法 $alert, $confirm 和 $prompt,合并三个参数为一个,并对应定义全局方法:alert、confirm、prompt(官方文档中的配置参数全部可用)。

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)
})

表单校验

  • 自定义校验规则
    rules: {
      pass: [
        { validator: validatePass, trigger: 'blur' }
      ]
    }
    该案例将会对pass字段进行自定义的validatePass校验
  • 校验方法
    • elValidate.checkPhoneNumber
      { validator: this.elValidate.checkPhoneNumber, trigger: 'change' } //校验电话号码
    • elValidate.checkIdCardNumber
      { validator: this.elValidate.checkIdCardNumber, trigger: 'change' } //校验电话身份证
    • elValidate.checkSpechars

      { validator: this.elValidate.checkSpechars, trigger: 'change' }//特殊符号校验
    • elValidate.checkUnifiedSocialCreditCode

      { validator: this.elValidate.checkUnifiedSocialCreditCode, trigger: 'change' } //统一社会信用代码校验

Vue相关方法(mixin)

  • resetData()
    this.resetData('dataList')
    初始化数据对象。暴露全局方法resetData,接收一个字符串,为data对象里的数据key值,该案例会将当前vue页面实例的data对象中的dataList数据设置为页面初始加载的状态。也可用来在关闭dialog时清空dialog里的数据对象。

Vue相关方法(prototype)

axios

对axios进行封装,自动化提示错误消息

请求方法

公共参数:

{
  url: string;// 请求路径
  headers?: any;// 配置请求头;
  ignoreInterceptRes?: boolean; // 是否拦截非成功返回,默认拦截
  checkLogin?: boolean; // 是否检查登录,默认不检查
  ignoreToken?:boolean;  //是否忽略在header里传递token,默认传递
  cache?:boolean;  //是否缓存,默认不缓存
}
  • GET方法
    import { request } from 'common-plugin';
    request.$get({
      url:'/getData',
      data:{}
    })
  • POST方法
    import {request } from 'common-plugin'
    return request.$post({
      url:'/getData',
      data:{}
    })
    独有参数
    {
      isForm?: boolean; // 是否表单提交,默认json提交
    }
  • PUT方法
    import { request } from 'common-plugin';
    request.$put({
        url:'/put'
    })
  • DELETE方法
    import { request } from 'common-plugin';
    request.$delete({
        url:'/delete'
    })

返回数据格式

{
  code: number,
  msg: string,
  data: any
}

若返回数据格式不正确,控制台会提示警告,并且会影响公共的请求错误处理

响应拦截

默认拦截所有返回非成功码的请求对应做以下处理:

  • 提示

    默认会提示用户错误信息:

    this.msg({message:res.msg})

    该提示可以通过请求配置中的 ignoreInterceptRes 参数配置是否弹出

  • 拦截未登录(暂未确定确定的状态码)

    拦截到未登录的状态码时会提示未登录,提示框关闭后会跳转登录页面

    Vue.prototype.msg({
      message: '检测到您还未登录,即将为您跳转到登录页面...',
      type: 'error',
      duration: 2000,
      onClose: () => {
        window.location.href = Vue.prototype.globalUrl.mall + '/logout.html'
      }
    })

工具包

定义全局可用工具包tyPlugin,将常用的方法封装。

  • currencyFormat 金额格式化
    this.tyPlugin.currencyFormat('1231312') // 1,231,312.00
  • DelCurrencyFormat 删除千位符
    this.tyPlugin.DelCurrencyFormat('1,231,312.00') // 1231312.00
  • convertCurrency 金额大写
    this.tyPlugin.convertCurrency('1231312') // 壹佰贰拾叁万壹仟叁佰壹拾贰元整
  • urlStringToObj URL字符串转化为对象
    this.tyPlugin.urlStringToObj('localhost:8080/as?a=1&b=2') // {a: "1", b: "2"}
  • objectToQueryString 将对象转化成查询参数
    this.tyPlugin.objectToQueryString({ a: 12, b: 3 }) // a=12&b=3
  • escape 字符串编码
    this.tyPlugin.escape('http://localhost:8080/#/') // http%3A//localhost%3A8080/%23/
  • unescape 字符串解码
    this.tyPlugin.unescape('http%3A//localhost%3A8080/%23/') // http://localhost:8080/#/
  • midHide 数据隐藏
    this.tyPlugin.midHide('12345678901',3,3) // 123*****901
    该方法接收三个参数,第一个目标字符串为必填参数,第二个开头显示的字符数为选填,第三个末尾显示的字符数为选填,默认为首3尾4。
  • getAllStyle 获取元素的计算样式
    this.tyPlugin.getAllStyle(dom) // CSSStyleDeclaration实例
  • getDomSPInfo 获取元素大小及其相对于视口的位置。
    this.tyPlugin.getDomSPInfo(dom) // DOMRect实例
  • setSessionStorage sessionstorage里面存数据
    this.tyPlugin.setSessionStorage('userData',{:name:'john'}) 
    接收两个参数,第一个参数为key值,第二个参数为value值。
  • getSessionStorage sessionstorage里面取数据
    this.tyPlugin.getSessionStorage('userData') 
    接收一个参数,要获取的数据的key值
  • debounce 函数防抖,触发高频事件后n秒内函数只会执行一次,如果n秒内高频事件再次被触发,则重新计算时间
    this.tyPlugin.debounce(Function,time) 
    接收两个参数,第一个为要执行的函数,第二个可选参数,为延时秒数,默认200ms
  • jsonClone 数据克隆
    this.tyPlugin.jsonClone(data) 
    接收要克隆的数据,返回克隆后的数据
  • getDayCount 获取传入时间所在月有几天
    this.tyPlugin.getDayCount(data) 
  • initObj 初始化对象参数
    this.tyPlugin.initObj(target: any, val?: any) 
    接收两个参数,第一个为要修改的目标对象,第二个为对比参数,target要置为val的值。若不传第二个参数,默认置为''
  • getDateArr 获取时间数组
    this.tyPlugin.getDateArr() 
    返回值:YYYY,MM,DD
  • getDateObj 获取时间对象
    this.tyPlugin.getDateObj(str?: string | number) 
    返回值Date实例 参数默认为当前时间
  • bankNumberFormat 格式化银行卡账号
    this.tyPlugin.bankNumberFormat(str) 
    返回由空格隔开的银行卡号码:1111 2222 3323 3432 2434
  • dataListMerge 数据合并
    this.tyPlugin.dataListMerge(data1,data2,key) 
    根据key字段,合并data1和data2数组
  • isDomInView 动态监测DOM元素是否在当前视野中
    this.tyPlugin.isDomInView(config: {
      dom: Element;
      change(data: { data: boolean }): void;
    })
    dom为要监测的dom元素,change为回调函数,参数为Boolean
  • scrollDirection 动态监测页面滚动的方向

    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
      this.tyPlugin.validate.checkIdCardNumber(str:string|number):boolean
      检测传入的身份证号码是否合法
    • tyPlugin.validate.checkPhoneNumber
      this.tyPlugin.validate.checkPhoneNumber(str:string|number):boolean
      检测传入的手机号码是否合法
    • tyPlugin.validate.isFloatNumber
      this.tyPlugin.validate.isFloatNumber(str:string|number):boolean
      小数数字校验
    • tyPlugin.validate.isIntNumber
      this.tyPlugin.validate.isIntNumber(str:string|number):boolean
      整数数字校验
    • tyPlugin.validate.checkUnifiedSocialCreditCode
      this.tyPlugin.validate.checkUnifiedSocialCreditCode(str:string):boolean
      统一社会信用代码校验
    • tyPlugin.validate.isNoSpechars
      this.tyPlugin.validate.isNoSpechars(str:string):boolean
      特殊字符校验,包括以下字符:
          const regEn = /[`~!@#$%^&*()_+<>?:"{},./;'[\]]/img
          const regCn = /[·!#¥(——):;“”‘、,|《。》?、【】[\]]/img
  • tyPlugin.equipmenttyPlugin.equipment返回一个对象:包含以下校验方法:
    • tyPlugin.equipment.isIOS
      this.tyPlugin.equipment.isIOS():boolean
      检测当前设备是否是ios
    • tyPlugin.equipment.isMobile
      this.tyPlugin.equipment.isMobile():boolean
      检测当前设备是否是移动端
  • tyPlugin.platform

    tyPlugin.platform返回一个对象:包含以下校验方法:

    • tyPlugin.platform.isWeChat
      this.tyPlugin.platform.isWeChat():boolean
      检测当前平台是否是微信

VUEX

  • 注意

    • 不要改变src下边的store文件夹名和store文件夹下面的index.ts文件名!
  • getStoreData

this.getStoreData('userInfo')

获取vuex里的数据

  • setStoreData
this.setStoreData('userInfo',val)

设置vuex的数据

filter 过滤器

主要用来格式化数据:

<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
自动聚焦
<input v-focus/>

vue-router

说明

  • 系统内部的跳转,统一使用<router-link>组件

方法

  • routeBack
  this.routeBack() //返回上一页
  • isNameInRouters
  this.isNameInRouters(index:string):boolean //当前路由以及嵌套路由是否含有name为index的页面。
  • isItemInRouterMeta
  this.isItemInRouterMeta(index:string|array):boolean //当前路由以及嵌套路由的meta数据里是否包含index的数据,入参可以是字符串,也可以是字符串组成的数组。
  • getParams
  this.getParams():any //获取params数据,并且刷新页面不会丢失
  • setQuery
  this.setQuery(data):viod //设置query数据

页面跳转

  • router-link
      <router-link to="/foo">Go to Foo</router-link>
  • 编程式导航
    this.$router.push({
      path: '/index'
    })

路由传参

  • query传参

    • router-link
      <router-link :to="{path:'/financial',query:{index:0}}">融资超市</router-link>
    • 编程式
      this.$router.push({
        path: '/index',
        query: {
          bankId: 12121
        }
      })
  • params传参

    params传参页面手动刷新后会丢失!

    • router-link
      <router-link :to="{ name: 'user', params: { userId: 123 }}">User</router-link>
    • 编程式
      this.$router.push({
        name: 'index',
        params: {
          bankId: 12121
        }
      })
  • 两种传参方式区别 query传参会在地址上显示,params传参不会

路由接收参数

  • query
    this.$route.query
  • params
    this.$route.params

组件

  • wait-line

     <wait-line></wait-line>

    有ajax请求的时候自动在组件顶部出现加载条

  • ty-ad

     <ty-ad></ty-ad>

    广告组件

    • attrs
    imgUrl:图片路径
    link:链接地址

注意事项

Date

因为各个浏览器对时间字符串格式要求不同的原因,注意以下事项:

  • 如果要将时间字符串转化为时间对象,要调用tyPlugin.getDateObj(str)来获取,不可直接new Date(str);
  • 如果要将时间戳转化为时间对象,那么入参必须为number类型。
1.0.33

2 years ago

1.0.32

2 years ago

1.0.31

2 years ago

1.0.30

2 years ago

1.0.29

3 years ago

1.0.28

3 years ago

1.0.27

3 years ago

1.0.26

3 years ago

1.0.25

3 years ago

1.0.24

4 years ago

1.0.23

4 years ago

1.0.22

4 years ago

1.0.21

4 years ago

1.0.20

4 years ago

1.0.19

4 years ago

1.0.18

4 years ago

1.0.17

4 years ago

1.0.16

4 years ago

1.0.15

4 years ago

1.0.14

4 years ago

1.0.13

4 years ago

1.0.12

4 years ago

1.0.11

4 years ago

1.0.10

4 years ago

1.0.9

4 years ago

1.0.8

4 years ago

1.0.7

4 years ago

1.0.6

4 years ago

1.0.5

4 years ago

1.0.4

4 years ago

1.0.3

4 years ago

1.0.2

4 years ago

1.0.0

4 years ago