全局监听扫码枪的扫码数据
在 src 下新建文件 scanCode.js,并在 main.js 引入即可
scanCode.js
import store from './store'
function scanCode() {
let str = ''
document.onkeydown = function() {
if (event.target.tagName !== 'BODY') {
str = ''
} else {
if (event.keyCode !== 13) {
if (event.keyCode >= 32 && event.keyCode <= 126) {
let k = event.key
str += k
}
} else {
if (str) {
store.commit('scanCode/SET_SCANSTRING', str)
}
str = ''
}
}
}
}
export default scanCode()
main.js
import Vue from 'vue'
import App from './App'
import store from './store'
import router from './router'
import './scanCode' // 扫码
Vue.config.productionTip = false
new Vue({
el: '#app',
router,
store,
render: h => h(App)
})
增加扫码的vuex
在modules
中新建文件scanCode.js
,并在getters.js
中增加scanString: state => state.scanCode.scanString
export default {
namespaced: true,
state: {
// 扫码的值
scanString: ''
},
mutations: {
SET_SCANSTRING: (state, scanString) => {
state.scanString = scanString
}
}
}
监听vuex
中scanString
的变化
export default {
computed: {
scanString() {
return this.$store.getters.scanString
}
},
watch: {
scanString(s) {
if (s) {
setTimeout(() => {
// 触发事件 你要做的事
alert(s)
// 执行结束后重复为空
this.$store.commit('scanCode/SET_SCANSTRING', '')
}, 100)
}
}
}
}