I am very new to Vue.js and wrapping my head around method event handling.
What my function is doing is to read a barcode using web camera input and display its raw content.
The function works fine if I just render the raw content. However, if I try to transform the raw content to a more readable form. I am getting the following error:
TypeError: Cannot read property '1' of null when calling formatBarcode method.
I am pretty sure it's probably not even related to Vue.js in particular but a common JS problem.
html
<div id="scan">
<div class="row m-b-1">
<div class="col-sm-6">
<video id="preview"></video>
<h5>Camera</h5>
<ul>
<li v-for="camera in cameras">
<span v-if="camera.id == activeCameraId" :title="formatName(camera.name)" class="active">{{ camera.name }}</span>
</li>
</ul>
</div>
<div class="col-sm-6">
<h5>Scans</h5>
<transition-group name="scans" tag="ul">
<li v-for="scan in scans" :key="scan.date" :title="scan.content">{{ formatBarcode(scan.content) }}</li>
</transition-group>
</div>
</div>
</div>
JS
var app = new Vue({
el: '#scan',
data: {
scanner: null,
activeCameraId: null,
cameras: [],
scans: []
},
mounted: function() {
var self = this;
self.scanner = new Instascan.Scanner({
video: document.getElementById('preview'),
scanPeriod: 5
});
self.scanner.addListener('scan', function(content) {
self.scans.unshift({
date: +(Date.now()),
content: content
});
});
Instascan.Camera.getCameras().then(function(cameras) {
self.cameras = cameras;
if (cameras.length > 0) {
self.activeCameraId = cameras[0].id;
self.scanner.start(cameras[0]);
} else {
console.error('No cameras found.');
}
}).catch(function(e) {
console.error(e);
});
},
methods: {
formatBarcode: function(content) {
const regex = /(01)(\d{14}|\d{0}})(21)(\d{10}|\d{0})/g;
let m;
while ((m = regex.exec(content)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
}
return `Group1: (${m[1]}) ${m[2]} Group: (${m[3]}) ${m[4]}`;
}
}
});
This is the regex I'm trying to test https://regex101.com/r/SvCs5t/3
Working fiddle to test the regex transformation https://jsfiddle.net/o01474u2/
moutside the while loop. Any fix for that?