我想将扫描的值发送到当前聚焦的输入字段。扫描仪放置在组件内部,该组件放置在
App.vue
旁边的 router-view
中,因此我始终可以在任何导航路线中访问扫描仪。
<template>
<v-container>
<router-view></router-view>
<FABScanner :visible="true" /> <!-- Component -->
</v-container>
</template>
对于扫描仪,我使用
StreamBarcodeReader
中的 vue-barcode-reader
。
<template>
<div>
<v-fab-transition>
<v-btn v-show="visible" class="mb-16" color="warning" fab bottom right absolute @click="showCamera = !showCamera">
<v-icon>fa-solid fa-barcode</v-icon>
</v-btn>
</v-fab-transition>
<StreamBarcodeReader v-if="showCamera" @decode="(a, b, c) => onDecode(a, b, c)" @loaded="() => onLoaded()" />
</div>
</template>
<script>
import { StreamBarcodeReader } from "vue-barcode-reader";
export default {
components: { StreamBarcodeReader },
props: {
visible: { type: Boolean, required: false, default: false },
value: { type: String, required: false, default: undefined }
},
data() {
return {
showCamera: false,
timeout: undefined,
text: ""
}
},
methods: {
onDecode(a, b, c) {
this.text = a;
if (this.timeout) clearTimeout(this.timeout)
this.timeout = setTimeout(() => {
if (this.text === a) {
this.text = "";
}
}, 5000);
this.$root.$emit('showSnackBar', { color: 'success', text: `${this.text}` });
this.showCamera = false
},
onLoaded() {
console.log('Camera loaded.')
},
}
}
</script>
由于我有各种输入,我无法使用
$refs
来更改输入的值。所以我尝试像这样改变DOM
中的值
onDecode(a, b, c) {
this.text = a;
if (this.timeout) clearTimeout(this.timeout)
this.timeout = setTimeout(() => {
if (this.text === a) {
this.text = "";
}
}, 5000);
this.$root.$emit('showSnackBar', { color: 'success', text: `${this.text}` });
this.showCamera = false
const focused = document.activeElement
if (!focused) return
focused.value = this.text
},
这会更改值,但不会触发输入内部的
@update
。
我终于找到了实现这一目标的方法。
通过使用
vuex
存储我可以设置和获取值。通过存储状态上的 watch
函数,我现在可以处理值的更改,从而使用 $refs
更新输入值。