Vue只能輸入數字

舞動乾坤發表於2018-11-21
<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title></title>
		<script src="./js/vue.js" type="text/javascript" charset="utf-8"></script>
	</head>

	<body>

		<div id="demo">
			<input type="text" placeholder="只能輸入正整數" @input="change" @change="change" :value="inpNum" />
		</div>
		<script type="text/javascript">
			new Vue({
				el: '#demo',
				data: {
					oldNum: ''
				},
				computed: {
					inpNum() {
						return this.oldNum
					}
				},
				methods: {
					change(event) {
						let val = event.target.value.trim()
						// 只能是正整數或空,可根據需求修改正則   
						//item = e.target.value.replace(/[^\d]/g,'')
						if(/^[1-9]\d*$|^$/.test(val)) {
							this.oldNum = val
						} else {
							event.target.value = this.oldNum
						}
					}
				}
			})
		</script>

	</body>

</html>
複製程式碼

相關文章