問題背景:
快應用中如何實作控制input輸入,超過規定字數就彈窗提示且無法輸入超過規定的字數?
實作方案:
可通過this.$watch()監測input元件的輸入值和@change事件,當輸入值超過限定字數給出彈窗提示,并強制将輸入的值改為限定字數内。
實作代碼:
<template>
<div class="container">
<text>僅支援輸入5個值</text>
<input class="input-text" id="text1" value="{{content}}" @change="handleInputValueChanged"></input>
</div>
</template>
<style>
.container {
flex: 1;
flex-direction: column;
align-items: center;
}
.input-text {
height: 100px;
width: 85%;
border: 1px solid #000000;
font-size: 80px;
}
</style>
<script>
import prompt from '@system.prompt';
module.exports = {
data: {
content: '',
inputText: '',
},
onInit() {
this.$page.setTitleBar({ text: '' })
},
test(e) {
this.$watch('this.content', 'handleInputValueChanged')
},
handleInputValueChanged: function (e) {
this.content = e.value;
console.log('handleInputValueChanged:' + this.content);
if (this.content.length === 5) {
console.log('value length greater than 5');
prompt.showToast({
message: "消息最長為5",
gravity: 'center'
})
this.inputText = this.content
}
if (this.content.length > 5) {
this.content = this.inputText
}
},
}
</script>