Vue-Cleave - 在Vue中使用CleaveJS格式化你的输入内容

项目地址:https://github.com/jrainlau/vue-cleave

What’s CleaveJS?

CleaveJS是最近github上的一个热门项目,在短短的一个多月中star数达到了2500+,且保持着强劲的上升势头。它的主要目的是

Format input text content when you are typing
格式化你的输入内容

可以查看官方的在线DEMO进行体验。

Vue-Cleave

官方的CleaveJS只提供了原生JSReactJS版本的,看样子也准备出AngularJS版的了。但是当我把VueJS版本的pullrequest过去之后,却得到了这么一条答复:

Thanks for playing cleave with vue.js. Vue.js is an amazing framework but for now, we will just focus on what we can handle.

So we will not add this support in the original repo, will close this, cheers.

看来只好自己独立发布,为VueJS社区作贡献了……

Usage

直接引用项目的例子作为展示。
首先建立一个父组件,命名为App.vue,其代码如下:

<!-- App.vue -->

<template>
  <Cleave :options='cleaveOptions' v-model='formatedValue'></Cleave>
</template>

<script>
import Cleave from './components/cleave.vue'

export default {
  data() {
    return {
      formatedValue: '',
      cleaveOptions: {
        numeral: true,
        numeralDecimalScale: 4
      }
    }
  },
  watch: {
    'formatedValue': (val) => {
      console.log(val)
    }
  },
  components: {
    Cleave
  }
}

</script>

然后呢?
没有了。

使用方式非常简单,只需要把cleave.vue组件import进来进行引用,然后通过动态props的方式在父组件App.vue里面把写好的自定义cleaveOptions传到<Cleave/>里面就行了。我们可以把<Cleave/>当作一个普通的<input/>元素直接进行使用。

对于自定义的cleaveOptions,其设置的内容和官方文档是相同的,直接照着设置即可。

PS:对于格式化电话号码的问题,需要进入到cleave.vue文件,手动引入对应国家的addon包:

require('../lib/addons/phone-type-formatter.{country}')

License

Vue-Cleave is licensed under the Apache License Version 2.0

Last but not least…

由于引用包和官方的同步,而官方的包仍然有一些小bug,所以Vue-Cleave也会因此带有瑕疵,但我会尽量及时更新维护,也欢迎大家共同维护,一起建立更加完善的VueJS生态圈。

水平有限,如有发现任何错漏还请指点一二。我是Jrain,欢迎关注我的专栏,不定期分享自己的学习体验,开发心得,搬运墙外的干货。下次见啦,谢谢大家!

    原文作者:jrainlau
    原文地址: https://segmentfault.com/a/1190000005984648
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞