一个分块input组件
<template>
<view class="line">
<view class="wrapper" v-for="(item, index) in inputBox" :key="index">
<input
class="input"
v-model="item.value"
type="text"
:focus="item.focus"
@input="onInput(index)"
maxlength="1"
/>
</view>
</view>
</template>
<script>
export default {
name: 'SplitInputBox',
model: {
prop: 'value',
event: 'change',
},
props: {
digit: {
type: Number,
default: 4,
},
},
data() {
return {
inputBox: [{ value: '', focus: true }],
}
},
methods: {
onInput(index) {
const value = this.inputBox[index].value
if (value.length === 1 && index < this.$props.digit - 1) {
this.inputBox[index].focus = false
this.inputBox[index + 1].focus = true
} else if (value.length === 0 && index > 0) {
this.inputBox[index].focus = false
this.inputBox[index - 1].focus = true
} else {
this.inputBox[index].focus = false
return
}
},
},
computed: {
fullValue: {
get: function () {
let value = ''
this.inputBox.forEach((item) => {
value += item.value
})
return value
},
set: function (newValue) {
const values = newValue.split('')
if (values.length !== this.$props.digit) {
console.warn(`Error: new value should be at least ${this.$props.digit} digits`)
return
}
for (let i = 0; i < values.length; i++) {
this.inputBox[i] = values[i]
}
},
},
},
watch: {
fullValue(nv) {
this.$emit('change', nv)
},
},
created() {
if (this.$props.digit < 1) console.warn('Error: digit should be at least 1')
const unit = { value: '', focus: false }
for (let i = 0; i < this.$props.digit - 1; i++) {
this.inputBox.push(JSON.parse(JSON.stringify(unit)))
}
},
}
</script>
<style lang="less" scoped>
.line {
width: 100%;
display: flex;
flex-flow: row nowrap;
justify-content: center;
align-items: center;
.wrapper {
padding: 0 24rpx;
.input {
width: 80rpx;
height: 80rpx;
border: 2rpx solid #333333;
border-radius: 16rpx;
background: #ffffff;
text-align: center;
}
}
}
</style>
Chinese 🇨🇳 / Dictatorial Admin / Mastodon Code Contributor / 摸鱼技术布道师
Steam: https://steamcommunity.com/id/MashiroBest
Epic: https://store.epicgames.com/en-US/u/d211c824cbd94aaeba898db6bb823ff7
原批交流群:966322309