This repository has been archived by the owner on Oct 17, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 37
/
component.js
114 lines (107 loc) · 2.82 KB
/
component.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
import Cleave from 'cleave.js'
import {defineComponent, h} from 'vue';
export default defineComponent({
name: 'cleave',
compatConfig: {
MODE: 3
},
render() {
return h('input', {
type: 'text',
value: this.cleave ? this.cleave.properties.result : this.modelValue,// Cleave.js will set this as initial value
onBlur: this.onBlur,
})
},
props: {
modelValue: {
default: null,
required: true,
validator(value) {
return value === null || typeof value === 'string' || value instanceof String || typeof value === 'number'
}
},
// https://github.com/nosir/cleave.js/blob/master/doc/options.md
options: {
type: Object,
default: () => ({})
},
// Set this prop as `false` to emit masked value
raw: {
type: Boolean,
default: true
},
},
emits: ['blur', 'update:modelValue'],
data() {
return {
// cleave.js instance
cleave: null,
// callback backup
onValueChangedFn: null,
}
},
mounted() {
/* istanbul ignore if */
if (this.cleave) return;
this.cleave = new Cleave(this.$el, this.getOptions(this.options));
},
methods: {
/**
* Inject our method in config options
*/
getOptions(options) {
// Preserve original callback
this.onValueChangedFn = options.onValueChanged;
return Object.assign({}, options, {
onValueChanged: this.onValueChanged
});
},
/**
* Watch for value changed by cleave and notify parent component
*/
onValueChanged(event) {
let value = this.raw ? event.target.rawValue : event.target.value;
this.$emit('update:modelValue', value);
// Call original callback method
if (typeof this.onValueChangedFn === 'function') {
this.onValueChangedFn.call(this, event)
}
},
onBlur() {
this.$emit('blur', this.modelValue)
}
},
watch: {
/**
* Watch for any changes in options and redraw
*/
options: {
deep: true,
handler(newOptions) {
this.cleave.destroy();
this.cleave = new Cleave(this.$el, this.getOptions(newOptions));
this.cleave.setRawValue(this.modelValue)
}
},
/**
* Watch for changes from parent component and notify cleave instance
*/
modelValue(newValue) {
/* istanbul ignore if */
if (!this.cleave) return;
// when v-model is not masked (raw)
if (this.raw && newValue === this.cleave.getRawValue()) return;
// when v-model is masked (NOT raw)
if (!this.raw && newValue === this.$el.value) return;
// Lastly set newValue
this.cleave.setRawValue(newValue);
}
},
beforeUnmount() {
/* istanbul ignore if */
if (!this.cleave) return;
this.cleave.destroy();
this.cleave = null;
this.onValueChangedFn = null;
},
})