Vue Component Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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