提交 | 用户 | 时间
|
5030f3
|
1 |
<template> |
Y |
2 |
<el-form size="large" :inline="true" label-width="68px" @submit.native.prevent> |
|
3 |
<el-form-item v-for="(item, index) in scanList" |
|
4 |
:key="index" |
|
5 |
label-width="200" |
|
6 |
label="箱体码" |
|
7 |
:prop="item.value" |
|
8 |
style="align-content: center" |
|
9 |
@focus="handleFocus(index)"> |
|
10 |
<input v-model="item.value" |
|
11 |
ref="scanInput${index}" |
|
12 |
style="height: 39px; width: 300px" |
|
13 |
placeholder="请扫描箱体码" |
|
14 |
/> |
|
15 |
</el-form-item> |
|
16 |
</el-form> |
|
17 |
</template> |
|
18 |
|
|
19 |
<script> |
|
20 |
export default { |
|
21 |
data() { |
|
22 |
return { |
|
23 |
scannerFlag: false, |
|
24 |
scanList: [ |
|
25 |
{ value: '' }, |
|
26 |
{ value: '' }, |
|
27 |
// 可以根据需要增加更多的项 |
|
28 |
], |
|
29 |
focusedIndex: 0, // 当前聚焦的input索引 |
|
30 |
}; |
|
31 |
}, |
|
32 |
mounted() { |
|
33 |
this.focusScanInput(this.focusedIndex); |
|
34 |
this.setFocus() |
|
35 |
this.$refs.scanInput$index.addEventListener('keydown',this.handleScannerInput) |
|
36 |
}, |
|
37 |
beforeDestroy() { |
|
38 |
this.$refs.scanInput$index.removeEventListener('keydown',this.handleScannerInput) |
|
39 |
}, |
|
40 |
watch: { |
|
41 |
// 监听scanList的变化,如果发现焦点索引超出范围,则自动聚焦到最后一个输入框 |
|
42 |
scanList: { |
|
43 |
deep: true, |
|
44 |
handler(newList) { |
|
45 |
if (this.focusedIndex >= newList.length) { |
|
46 |
this.focusedIndex = newList.length - 1; |
|
47 |
this.$nextTick(() => { |
|
48 |
this.focusScanInput(this.focusedIndex); |
|
49 |
}); |
|
50 |
} |
|
51 |
}, |
|
52 |
}, |
|
53 |
}, |
|
54 |
|
|
55 |
methods: { |
|
56 |
refresh() { |
|
57 |
location.reload(); |
|
58 |
}, |
|
59 |
setFocus(){ |
|
60 |
this.$nextTick(()=>{ |
|
61 |
this.$refs.inputdata.focus() |
|
62 |
}) |
|
63 |
}, |
|
64 |
handleScannerInput(event){ |
|
65 |
if (this.scannerFlag){ |
|
66 |
this.barcode = '' |
|
67 |
this.$refs.inputdata.value = '' |
|
68 |
this.scannerFlag = false |
|
69 |
} |
|
70 |
const input = event.target |
|
71 |
const inputValue = input.value |
|
72 |
this.item.value = inputValue |
|
73 |
if (event.key === 'Enter'){ |
|
74 |
this.scannerFlag = true |
|
75 |
console.log('条码:',this.item.value) |
|
76 |
//扫描完成 |
|
77 |
} |
|
78 |
}, |
|
79 |
|
|
80 |
handleFocus(index) { |
|
81 |
this.focusedIndex = index; |
|
82 |
}, |
|
83 |
focusScanInput(index) { |
|
84 |
this.$refs[`scanInput${index}`][0].focus(); |
|
85 |
}, |
|
86 |
}, |
|
87 |
}; |
|
88 |
</script> |
|
89 |
<!--在这个例子中,我们使用了一个数组scanList来动态生成多个输入框。通过handleFocus方法更新当前聚焦的输入框索引, |
|
90 |
并通过watch来监听scanList的变化,以确保如果新添加的输入框超出了原有的索引范围, |
|
91 |
我们可以自动聚焦到最后一个输入框上。focusScanInput方法用于设置真实DOM的焦点。--> |