Giter VIP home page Giter VIP logo

vue-cleave-component's Introduction

Vue Cleave Component

downloads npm-version github-tag license build codecov

Vue.js component for Cleave.js

Demo on JSFiddle

Version matrix

Vue.js version Package version Branch
2.x 2.x 2.x
3.x 3.x master

Features

  • Reactive v-model value
    • You can change input value programmatically
  • Reactive options
    • You can change config options dynamically
    • Component will watch for any changes and redraw itself
  • Compatible with Bootstrap, Bulma or any other CSS framework
  • Works with validation libraries
  • Option to disable raw mode to get masked value

Installation

npm install vue-cleave-component --save

Usage

<template>
    <div>
        <cleave v-model="cardNumber"
                :options="options"
                class="form-control"
                name="card"/>
    </div>
</template>

<script>
    import Cleave from 'vue-cleave-component';

    export default {
        data() {
            return {
                cardNumber: null,
                options: {
                    creditCard: true,
                    delimiter: '-',
                }
            }
        },
        components: {
            Cleave
        }
    }
</script>

As plugin

import {createApp} from 'vue';
import Cleave from 'vue-cleave-component';
// your app initilization logic goes here
const app = createApp({});
app.use(Cleave);
app.mount('#app');

This will register a global component <cleave>

Available props

The component accepts these props:

Attribute Type Default Description
v-model String / Number / null null Set or Get input value (required)
options Object {} Cleave.js options
raw Boolean true When set to false; emits formatted value with format pattern and delimiter

Install in non-module environments (without webpack)

  • Include required files
<!-- cleave.js -->
<script src="https://cdn.jsdelivr.net/npm/cleave.js@1"></script>
<!-- Vue.js -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<!-- Lastly add this package -->
<script src="https://cdn.jsdelivr.net/npm/vue-cleave-component@3"></script>
<script>
    const app = Vue.createApp({});
    app.use(VueCleave);
    app.mount('#app');
</script>

Run examples on your localhost

  • Clone this repo
  • Make sure you have node-js >=18.9 and pnpm >=7.x pre-installed
  • Install dependencies pnpm install
  • Run webpack dev server npm start
  • This should open the demo page in your default web browser

Testing

  • This package is using Jest and vue-test-utils for testing.
  • Tests can be found in __test__ folder
  • Execute tests with this command npm test

Changelog

Please see CHANGELOG for more information what has changed recently.

Alternatives

If you feel this component heavy, then you can consider these packages.

License

MIT License

vue-cleave-component's People

Contributors

ankurk91 avatar japseyz avatar jorgenvatle avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

vue-cleave-component's Issues

SSR/Nuxt - Object(...) is not a function

I'm submitting a ...

[x] Bug report => search github for a similar issue or PR before submitting
[ ] Feature request
[ ] Other, please describe

Tell about your platform

  • Nuxt version: 2.15.3
  • Browser name and version : All Browsers
  • This package version : 3.x.x

Current behavior
Object(...) is not a function

image

Or is there a special way to use it with Nuxt?

Expected behavior
To work normally

Minimal reproduction of the problem with instructions
https://codesandbox.io/s/wonderful-solomon-tu6vz?file=/pages/index.vue

Please add changelogs

Hey @ankurk91,

Can you please add changelogs to future releases (even if it's just major version bumps) as it gives us an idea of what to look out for when upgrading.

Cheers

Feature Request - enter key emitter

I'm submitting a ... (check one with "x")

[ ] Bug report => search github for a similar issue or PR before submitting
[x] Feature request
[ ] Other, please describe

Current behavior
no emitter for enter key

Expected behavior
I feel like it may be useful to add an emitter for the enter key - this worked for me, I'm happy to make a PR, but didn't have permission.

image

Unable to use @click on vue-cleave-component text field

I'm unable to target a cleave input field to do some event handling - is there a workaround or something that I'm missing? Please note the @click in the cleave template component and the aFunction function.

My component:

<template>
  <div>
    <form v-on:submit.prevent="submitted">
      <cleave
	@click="aFunction"
	v-model="phoneNumber"
	class="textInput"
        :options="options"
        autocomplete="off"
	autofocus>
      </cleave>
      <input type="text" @click="getPosition"></input>
      <keyboard @numberEmitted="updateNumber" />
    </form>
  </div>
</template>

<script>
import Cleave from 'vue-cleave-component'
require('../../dependencies/cleave-phone-us.js')
import Keyboard from './Keyboard'

export default{
  data () {
    return {
      phoneNumber: null,
      options: {
        phone: true,
        phoneRegionCode: 'US'
      }
    }
  },
  components: {
    Cleave,
    Keyboard
  },
  methods: {
    updateNumber (passedNumber) {
       this.phoneNumber = passedNumber
    },
    aFunction (e) {
      // THIS IS WHAT I NEED TO DO
      console.log('This function works!') 
    }
  }
}

</script>

Detect KeyUp Fail

I am trying to detect keyup in cleave component but not works.

<cleave
    :raw="false"
    type="text"
    :placeholder="'__/__/__'"
    v-model="inputVal"
    :options="optionsdate"
    @keyup="emitVal"
  ></cleave>

I'm submitting a ... (check one with "x")

[X] Bug report => search github for a similar issue or PR before submitting
[ ] Feature request
[ ] Other, please describe

Tell about your platform

  • Vue.js version : 2.5.17
  • Browser name and version : Chrome 74
  • This package version : 2.1.2

Current behavior
Can detect keyup in component.

Expected behavior
Detect keyup to do ajax request

Minimal reproduction of the problem with instructions

V-model doesn't work correctly with number input on android phones

Issue Type

  • Bug report for android phones

Your Environment

  • My JsFiddle is based on the demo from the readme file of the repository!

Current behavior

  1. Insert a number in the number input field
  2. The referenced variable in v-model doesn't get updated
  • This bug can only be reproduced on android phones
  • The browser doesnt seem to matter

Expected behavior

  • Inserted value in number field should update the referenced variable in v-model correctly

Minimal reproduction of the problem with instructions

Current behaviour on a compouter
screen shot 2018-06-01 at 15 30 27

Current behaviour on android
screen shot 2018-06-01 at 15 30 27

How to include delimiters to the v-model's value?

I store the date values entered by the user in vuex. And I use these options to format the date:

cleaveOptions: {
    date: true,
    datePattern: ['d', 'm', 'y'],
    delimiter: '.'
}

And everything works correctly - delimiters are displayed along with digits. But delimiters do not become as part of the v-model. Instead, I see only 6 digits. Is there a way to include delimiters in the v-model as part of the date value?

Infinite loop updating value state on android devices

I'm submitting a ...

[x] Bug report => search github for a similar issue or PR before submitting
[ ] Feature request
[ ] Other, please describe
  • cleave.js version : 1.4.2
  • Vue.js version : 2.5.3
  • This package version : 2.1.0
  • On Android mobile phones

Current behavior

Hi,

I had problems with value changes not being detected on Android, and saw there were some fixes in Cleave.js through #11.
I updated to 2.1.0 (by the way, I had to change @blur.native to @blur for things to work, is this something that should be written in the CHANGELOG?)

I now have some kind of infinite loop when I type numbers in the input.
I can see that the updateValueState function in cleave.js is called in loops, whether i have the @blur listener or not, as well as the "value"'s props validator function (in vue-cleave.js). The numbers in the input jump around (if I have a "1" and add a "2" to make "12", i see the 2 added, removed, added, removed... in loops). In the value's props validator function called in loops, the value alternates between "1" and "12".

I use the component in the following way:

<cleave :id="'question'+question.id+'-'+item.id" :raw="true" :name="item.id" v-model.number="item.value" :options="{numeral: true, numeralDecimalMark: ',', delimiter: ' ', numeralPositiveOnly: true, numeralDecimalScale: 0}" @blur="roundValue()"></cleave>

On iOS or on desktop, this does not happen. It does happen on Desktop Chrome if I simulate using a GalaxyS5 device, but not another non-android device.

By removing the whole following block found in cleave-js inside updateValueState:

// fix Android browser type="text" input field
	        // cursor not jumping issue
	        if (owner.isAndroid) {
	            window.setTimeout(function () {
	                owner.element.value = newValue;
	                Util.setSelection(owner.element, endPos, pps.document, false);
	                owner.callOnValueChanged();
	            }, 1);

	            return;
	        }

the problem seems to go away.

I know this is probably a cleave.js bug, but since I'm using cleave through the vue-component I want to make sure it's not linked in any way to the vue component before submitting the issue upstream.

Could the original problem have been fixed on android phones, or maybe recent ones? Is it linked to the options I used?

I adapted the JsFiddle from #11 and reproduced the bug when using the GalaxyS5 device simulator on Chrome desktop:

https://jsfiddle.net/revhdn8x/7/

Thanks in advance.

Using with Vuelidate

  • Vue.js version : 2.5.2
  • Browser name and version : Chrome
  • This package version : 2.1.1

Hi,

I am trying to get vue-cleave-component to work with vuelidate but am running into an issue where the $dirty, $anyDirty and $error flags for vuelidate are all set on initialization. Because I display errors using these flags, this results in all inputs using cleave to show errors.

I see you have an example for vee-validate is there any possibility you may have tried this will vuelidate?

I tried hunting around to see if any one else had this issue but no luck and am not sure why this would happen so I was hoping you could point me in the right direction.

Thanks!

Add zeros on value

I'm submitting a ... (check one with "x")

[ ] Bug report => search github for a similar issue or PR before submitting
[x ] Feature request
[ ] Other, please describe

Tell about your platform
windows

  • cleave.js version : 1.x.x
    lastest
  • Vue.js version : 2.x.x
    lastest
  • Browser name and version : Chrome|Firefox|Safari x.x.x
    Chrome lastest
  • This package version : 2.x.x

Current behavior
I want suggest a new behavior for numbers when user typing money values, the component can complete with zeros when the user do not input decimal values.
For exemple: The value 1000 becomes 1000,00 when the component loose the focus.

Expected behavior

How to get credit card type?

In Cleave.js doc there is an option to get credit card type onCreditCardTypeChanged.
How to do it in vue-cleave-component?

Vee-Validate not fire error when input lost focus

I'm submitting a ... (check one with "x")

[x] Bug report => search github for a similar issue or PR before submitting
[ ] Feature request
[ ] Other, please describe

Tell about your platform

  • cleave.js version : 1.4.2
  • Vue.js version : 2.5.6
  • Browser name and version : Chrome 67|Firefox 61|
  • This package version : 2.0.1

Current behavior
vee-validate not fire error with rule Required when input lost focus

my code :

<div class="control has-icons-right">
            <cleave class="input"
                    :class="errors.has('quantity') ? 'is-danger': ''"
                    :options="options.quantity"
                    v-model="form.quantity"
                    name="quantity"
                    placeholder="Quantity"
                    data-vv-as="Quantity"
                    v-validate="'required'"></cleave>
            <span class="icon is-right has-text-danger"
                  v-if="errors.has('quantity')">
              <i class="fas fa-lg fa-exclamation-circle"></i>
            </span>
          </div>

Expected behavior
Cleave fire error

Minimal reproduction of the problem with instructions

https://jsfiddle.net/4ndcd0sc/10/

No htmlRef possibility to force focus ?

I'm submitting a ... (check one with "x")

[x] Bug report
[x] Feature request
[ ] Other, please describe

Tell about your platform

  • cleave.js version : 1.4.7
  • Nuxt version : 2.9.2
  • Browser name and version : Chrome|Firefox latest
  • This package version : ^2.1.3

Current behavior
No possibility to force focus

Minimal reproduction of the problem with instructions
Tried @Focus, autofocus, autofocus=true, passing a prop, etc ...

Issue with copy / paste

I'm submitting a ... (check one with "x")

[x] Bug report => search github for a similar issue or PR before submitting
[ ] Feature request
[ ] Other, please describe

Tell about your platform

  • Vue.js version : 2.6.10
  • Browser name and version : Chrome|Firefox|Safari x.x.x
  • This package version : 2.1.3

Current behavior
When I copy / paste into a phone formatted field, it strips out characters seemingly at random. In my clipboard, I have +1-123-456-7890, but when I paste, it gives +1 11

Expected behavior
When I paste, it should be the full formatted number.

Minimal reproduction of the problem with instructions
My component code is:

              <cleave
                v-model="User.settings.phoneNumber"
                :options="cleaveOptions"
                class="form-control"
                placeholder="Enter mobile number"
                id="myPhoneNumberInput"
              ></cleave>

and

      cleaveOptions: {
        phone: true,
        phoneRegionCode: "US",
        prefix: "+1"
      }

Vue3: Error in mounted hook

Hello,

Im using Vue3 - Vite.

Here is the error I get 👍

[Vue warn]: Unhandled error during execution of mounted hook 
  at <Cleave modelValue=null onUpdate:modelValue=fn options= {creditCard: true, delimiter: '-'}  ... > 
  at <CustomInput name="yearly_incomes" ref="yearlyIncomes" type="string"  ... > 
  at <Form class="space-y-16" onSubmit=fn<onSubmit> validation-schema= ObjectSchema {deps: Array(0), conditions: Array(0), _whitelist: ReferenceSet, _blacklist: ReferenceSet, exclusiveTests: {…}, …}  ... > 
  at <BaseTransition appear=false persisted=false onBeforeEnter=fn<onBeforeEnter>  ... > 
  at <Transition enter-active-class="animate__animated animate__fadeIn" > 
  at <Main> 
  at <InvestmentStep onVnodeUnmounted=fn<onVnodeUnmounted> ref=Ref< Proxy {handleButtonClick: <accessor>, handleValid: <accessor>, datas: <accessor>, formatCurrency: <accessor>, editPatrimony: <accessor>, …} > > 
  at <RouterView> 
  at <Main onVnodeUnmounted=fn<onVnodeUnmounted> ref=Ref< Proxy {_: <accessor>, $: <accessor>, $el: <accessor>, $data: <accessor>, $props: <accessor>, …} > > 
  at <RouterView> 
  at <OnboardingLayout> 
  at <App>
Uncaught TypeError: t2(...) is not a constructor

Do you know why ?

Error on Phone input

I'm getting an error when trying to use this component for a phone number input.

If you check out this fiddle and type in the field, you should see that the phone number is not formatting properly, and the error in the console: Uncaught TypeError: r.phoneFormatter.format is not a function
https://jsfiddle.net/eluce2/z7dfv3n6/7/

Release version with newer Cleave.js dependency for NPM

Hi,

Please, release a new version of your package with the latest version you support for Cleave.js

I saw you upgraded Cleave.js dependency to ^1.5.10 in master branch. There's one feature I need from version 1.5.5 and I'm currently using a direct dependency to your Github repository.

Thank you in advance.

Cleave version update

Hi
Can you please update Cleave version to the latest one ?
They have fixed backspace and cursor jumping issues in the parent library.

Thanks for great component.

Not working with vee-validate when using Ctrl +X shortcut

Hi
I'm using vue-cleave with vee-validate, when set required rule for input, if clear input using Ctrl + X shortcut then vee-validate not fire error, it's still working fine with Backspace and Delete.

How i can fix this ?

Thanks for great component.

Phone Delimiter Cursor Issue

Hello,
Thanks for updating the vue cleave to work with reactive data. I appreciate it!

I'm running into an issue after switching from the vue-bulma cleave component to your update. The following code worked properly from the vue-bulma cleave but lacked reactive data like I had expected.

<cleave v-model="from.phone" :options="{ phone: true, phoneRegionCode: 'US', delimiter: '-' }" class="form-control">

import CleavePhone from 'cleave.js/dist/addons/cleave-phone.us.js';

The issue occurs when numbers are typed and the second phone de-limiter is added, the text input cursor does not stay at the end of the input field as the user types and jumps back a character. So as a user types 987-765-7* the cursor will jump back to the second hyphen that was added as a delimiter. This wouldn't be an issue if users were smart and actually looked at what they were typing, but what is more likely to happen is that they will not notice that the cursor jumped back, continue typing, and end up entering the wrong phone number.

"vue": "^2.4.4", "vue-cleave": "^1.2.2", (Only used for phone addon) "vue-cleave-component": "^1.0.2",

I haven't tried using other delimiters or formats. If you need more information to replicate let me know.

Thanks again!

Using render props for complex components

In React there is a way to create complex components with render props.

For example, downshift.js uses that technique a lot. Where a function is passed as children into a component.

https://codesandbox.io/s/6z67jvklw3

I'm new to Vue and wonder if it's possible to achieve something similar.

My use-case is inspired by Buefy, where it's easy to create input fields.

<b-field label="Name">
    <b-input v-model="name"></b-input>
</b-field>

Currently, I had to use:

<div class="field">
  <div class="field-label is-normal">
    <label class="label">
      Price
    </label>
  </div>
  <div class="field-body">
    <div class="field">
      <div class="control is-clearfix">
        <cleave
          v-model="form.price"
          :class="['input', errors.price ? 'is-danger' : '']"
          :options="cleaveOptions"
        ></cleave>
      </div>
      <p v-if="errors.price" class="help is-danger">{{ errors.price[0] }}</p>
    </div>
  </div>
</div>

So the question, is there a way in Vue to achieve what render props do in React to combine multiple components?

v2.0.0 crashes browser when used with vee-validate

I'm submitting a ... (check one with "x")

[x] Bug report => search github for a similar issue or PR before submitting
[ ] Feature request
[ ] Other, please describe

Tell about your platform

  • Vue.js version : 2.5.12
  • Browser name and version : Chrome 67.0.3396.62

Current behavior
Combining vee-validate with vue-cleave-component crashes the browser.
This works fine on vue-cleave-component 1.0.3 but v2.0.0 or v2.0.1 cause a complete browser lockup and the cpu usage to spike as soon as the component is rendered.

Expected behavior
Vee-Validate & vue-cleave-component would work together

Minimal reproduction of the problem with instructions
Interestingly, while trying to setup the jsfiddle, it doesn't crash the browser, and instead gives us an actual error which may help diagnose what's been broken...

https://jsfiddle.net/4ndcd0sc/2/

Onblur, onFocus not working

<template>
     <cleave
          v-model="innerValue"
          :placeholder="placeholder"
          :size="size"
          class="ant-input"
          :class="classObject"
          :limitSize="limitSize"
          style="width: 100%"
          :disabled="disabled || readonly"
          :options="options"
          @input="changeHandler"
          @blur="blurHandler"
           @focus="focusHandler"
        ></cleave>
</template>


methods: {
    blurHandler($event) {
      this.$emit("blur", $event);
    },
    focusHandler($event) {
     this.$emit("focus", `$event);`
   }
}

Is this function available yet or am I doing something wrong?

Number Delimiter Cursor Issue

Hi,

I'm running in the same problem with the "numeral" type as describes for the phone number: #6

As soon as the second delimiter is added, the text input cursor does not stay at the end of the input field as the user types and jumps back a character per additional delimiter.

<cleave name="numeric_input"
        :options="{numeral: true, delimiter: '’', numeralThousandsGroupStyle: 'thousand', numeralPositiveOnly: true, numeralDecimalScale: 0, prefix: 'CHF ', noImmediatePrefix: true}"
        v-model="data.value"
        class="form-text">
</cleave>

Thank you for the integration of cleave.js!

Best,
Thomas

Adding to other components

I'm submitting a ... (check one with "x")

[ ] Bug report => search github for a similar issue or PR before submitting
[X] Feature request
[ ] Other, please describe

Tell about your platform

  • cleave.js version : 1.5.2
  • Vue.js version : 2.6.10
  • Browser name and version : Firefox 71.0
  • This package version : 2.1.3

Feature request
It would be a great enchantment if it would be possible to hook to another already defined components as well. Hooking into already existing components, such as:

<b-input v-model="model" :options="options"></b-input>

So that it applies the Cleave logic without applying any styling.

Vee-validate fires on page load and not @input or @blur

Tell about your platform

  • cleave.js version : 1.5.0
  • Vue.js version : 2.6.10
  • Browser name and version : Chrome 74.0.3729.169
  • This package version : 2.1.2

Current behavior
On page rendered, the error notice for vee-validate required rule shows up.

Expected behavior
The error notice for required shouldn't come up except after @input or @blur

<b-form-group
          label="Phone Number"
          label-for="phone_number"
          :state="errors.has('phone_number') ? 'invalid' : null"
          :invalid-feedback="errors.first('phone_number')"
        >
          <cleave
            v-model="user.phone_number"
            :options="cleave_phone"
            class="form-control"
            id="phone_number"
            v-validate="'required'"
            data-vv-as="Phone Number"
            name="phone_number"
            placeholder="Phone Number"
          ></cleave>
        </b-form-group>

I also set the option below for vee-validate

{
      events: 'input|blur'
}

vuex: blur or change event

Because I use Vuex, I normally use

<input :value="vuexState.item" @change="event => ActionToUpdateStateItem(event.target.value)">

instead of

How will I do that with vue-cleave-component?

This doesn't work:

<cleave class="input-is-transparent" placeholder="Beløb" :value="bonus.amount" :options="cleaveOptions.amount" @change="event => updateBonus({index, bonus, property: 'amount', value: event.target.value})"></cleave>

And I need the @change or some .lazy-type event so it input-method doesn't trigger on each key input

import phone lib addon

I'm submitting a ... (check one with "x")

[ ] Bug report => search github for a similar issue or PR before submitting
[ ] Feature request
[x] Other, please describe

Tell about your platform

  • cleave.js version : 1.x.x
  • Vue.js version : 2.x.x
  • Browser name and version : Chrome|Firefox|Safari x.x.x
  • This package version : 1.x.x

Current behavior

Expected behavior

Minimal reproduction of the problem with instructions
It's nice to mention we need to import phone lib to use phone options:
import 'cleave.js/dist/addons/cleave-phone.us';
I saw it on example, it would be nice to be on doc as well.
Thanks,

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.