Skip to content

Instantly share code, notes, and snippets.

@kntmr
Last active January 11, 2019 08:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kntmr/ddcdfc07e2ded69d5e590ed43473bf35 to your computer and use it in GitHub Desktop.
Save kntmr/ddcdfc07e2ded69d5e590ed43473bf35 to your computer and use it in GitHub Desktop.
Vue Component Example
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>Vue Component Example</title>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<style>
body {
text-align: center;
}
#main {
margin: 0 20%;
text-align: center;
}
th {
padding: 4px 10px;
text-align: left;
}
input {
width: 160px;
padding: 4px;
font-size: 16px;
text-align: right;
}
</style>
</head>
<body>
<div id="main">
<h2>Vue Component Example</h2>
<div align="center">
<table>
<tr>
<th>Positive num only</th>
<td><m-input-1></m-input-1></td>
</tr>
<tr>
<th>Positive num & Decimal</th>
<td><m-input-2></m-input-2></td>
</tr>
</table>
</div>
</div>
<script>
Vue.component('m-input-1', {
template: `
<input type="text" :size="size" :maxlength="maxlength" v-model="value" @keypress="validate" @input="value=format(value)" />
`,
props: {
size: {
type: Number,
default: 1
},
maxlength: {
type: Number,
default: 8
}
},
data () {
return {
value: ''
}
},
methods: {
validate (e) {
const charCode = (e.which) ? e.which : e.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
e.preventDefault()
} else {
return true
}
},
format (val) {
if (!val) {
return ''
}
const replaced = val.replace(/\D/g, '')
return replaced ? replaced : ''
}
}
})
Vue.component('m-input-2', {
template: `
<input type="text" :size="size" :maxlength="maxlength" v-model="value" @keypress="validate" @change="value=format(value)" />
`,
props: {
size: {
type: Number,
default: 1
},
maxlength: {
type: Number,
default: 5
}
},
data () {
return {
value: '',
prevValue: ''
}
},
methods: {
validate (e) {
const charCode = (e.which) ? e.which : e.keyCode
if ((charCode > 31 && (charCode < 48 || charCode > 57)) && charCode !== 46) {
e.preventDefault()
} else {
return true
}
},
format (val) {
if (!val) {
return this.prevValue = ''
}
if (/^([1-9]{1}[0-9]{0,1})(\.\d{0,2})?$/.test(val)) { // ##.##
return this.prevValue = val
}
if (/\.\d{3,}$/.test(val)) { // .### => .##
return this.prevValue = (Math.floor(parseFloat(val) * Math.pow(10, 2)) / Math.pow(10, 2)).toString()
}
return this.prevValue
}
}
})
const vm = new Vue({
el: "#main"
})
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment