欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

如何在Vue中使用CleaveJS格式化你的输入内容

程序员文章站 2022-12-14 14:55:14
what's cleavejs? cleavejs 是最近github上的一个热门项目,在短短的一个多月中star数达到了2500+,且保持着强劲的上升势头。...

what's cleavejs?

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

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

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

vue-cleave

官方的cleavejs只提供了 原生js reactjs 版本的,看样子也准备出 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

cleave.js is included under its apache license version 2.0

google libphonenumber is included under itsapache license version 2.0

last but not least...

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

项目地址:

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。