Troubleshooting: Vue.js component events not being detected in TypeScript

I'm encountering an issue with receiving events from a barcode reader, which I heavily referenced from a GitHub repository.

The problem lies in the fact that the events emitted by the BarcodeScanner component are not being captured by the enclosing component, a modified version of HelloWorld.vue. The Vue DevTools in the browser console indicate that the events are being properly emitted. However, the HelloWorld component does not respond to these events.

HelloWorld.vue:

<template>
  <div class="hello">
    <barcode-scanner @loaded="onLoaded" @decoded="onDecoded"/>
  </div>
</template>

<script lang="ts">
import {Component, Vue} from 'vue-property-decorator';
import BarcodeScanner from "@/components/BarcodeScanner.vue";

@Component({
  components: {BarcodeScanner}
})
export default class HelloWorld extends Vue {

  onLoaded() {
    console.log("Barcode scanner component has emitLoaded");
  }

  onDecoded(code: string) {
    console.log("Scanned code", code);
  }
}
</script>

<style scoped>
</style>

BarcodeScanner.vue:

<template>
  <div class="scanner-container">
    <div v-show="isLoaded">
      <video ref="scanner"></video>
      <div class="overlay-element"></div>
    </div>
  </div>
</template>

<script lang="ts">
import {Component, Emit, Ref, Vue} from "vue-property-decorator";
import {BrowserMultiFormatReader, Exception, Result} from "@zxing/library";

@Component
export default class BarcodeScanner extends Vue {

  @Ref("scanner") private scanner!: HTMLVideoElement;
  private isLoaded = false;
  private codeReader = new BrowserMultiFormatReader();
  readonly streamAPISupported = ("enumerateDevices" in navigator?.mediaDevices);

  @Emit("loaded") emitLoaded(): void {
    this.isLoaded = true;
  }

  @Emit("decoded") emitDecoded(code: string) {
    console.log("Decoded", code);
  }

  mounted() {
    if (!this.streamAPISupported) {
      throw new Exception("Media stream API not supported");
    }
    this.start();
    this.scanner.oncanplay = () => {
      this.emitLoaded();
      console.log("Scanner has loaded (BarcodeScanner component)");
    }
  }

  start(): void {
    this.codeReader.decodeFromVideoDevice(
        null,
        this.scanner,
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        (result: Result, err: Exception | undefined) => {
          if (result) {
            console.log(result);
            this.emitDecoded(result.getText());
          }
        }
    )
  }
}
</script>

<style scoped>
video {
  max-width: 100%;
  max-height: 100%;
}

.scanner-container {
  position: relative;
}

.overlay-element {
  position: absolute;
  top: 0;
  width: 100%;
  height: 100%;
  background: rgba(30, 30, 30, 0.5);
  -webkit-clip-path: polygon(
      0% 0%,
      0% 100%,
      20% 100%,
      20% 20%,
      80% 20%,
      80% 80%,
      20% 80%,
      20% 100%,
      100% 100%,
      100% 0%
  );
  clip-path: polygon(
      0% 0%,
      0% 100%,
      20% 100%,
      20% 20%,
      80% 20%,
      80% 80%,
      20% 80%,
      20% 100%,
      100% 100%,
      100% 0%
  );
}
</style>

Is there something obvious that I may be overlooking?

Answer №1

Solving the issue by recreating my Vue.js project and transferring the files mentioned above unexpectedly resolved the problem.

With a background in Java and more than twenty-five years of professional experience, I continue to be bewildered by certain aspects of modern front-end frameworks.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The error at core.js:4002 is a NullInjectorError with a StaticInjectorError in AppModule when trying to inject FilterService into Table

While exploring PrimeNg Table control in my application - as a beginner in PrimeNg & Angular, I encountered an error No provider for FilterService! shown below: core.js:4002 ERROR Error: Uncaught (in promise): NullInjectorError: StaticInjectorError(AppMo ...

How to selectively make properties optional in Typescript conditions

Currently, I am working on creating a utility type to unwrap nested monads of Options in my code. Here is the progress I have made so far: export interface Option<T> { type: symbol; isSome(): boolean; isNone(): boolean; match<U>(fn: Mat ...

AngularJS, sort through "afoo" excluding "foo"

I am attempting to implement a filter within an ng-repeat Main.HTML <table> <tr ng-repeat="param in MyParam | filter: UnrequestValue"> <td>{{param.Label}}</td> </tr> </table> Main.js MyParam: ...

Vuex computed property not updating when listening to getter

Does anyone know why my computed properties, which essentially just call a store getter with an ID, are not being re-computed when the store changes? The relevant computed property is 'isInCart' for a product: isInCart() { var isInCart = th ...

Are you still relying on outdated endpoint pagination with Vue and Laravel?

Currently, I am in the process of transitioning a Laravel app from using Blade files to implementing Vue. In one part of the app, we had used pagination for displaying users with a page parameter at the end of the endpoint URL. For instance: /store/api ...

Typescript counterpart of a collection of key-value pairs with string keys and string values

Within the API I'm currently working with, the response utilizes a data type of List<KeyValuePair<string, string>> in C#. The structure appears as shown below: "MetaData": [ { "key": "Name", &q ...

Troubleshooting: Unable to Open Page with Google Material Button in Angular 5

Currently, I'm facing an issue with a button that is not opening to a new site despite following what seems like simple steps. <button mat-raised-button href="https://www.google.com/" color="primary">Connect with Stripe</button> I even a ...

It appears that protractor-flake is programmed to re-run all tests instead of just the ones that have failed

Running tests using the latest version of "[email protected]", encountering failures during testing but the tests are rerunning again. No custom reporter used except Allure reporting. Below is the command used for running: protractor-flake --max-at ...

Heroku Woes: Vue-CLI Deployment Woes

I have been facing persistent challenges while trying to deploy my Node.js application with a Vue.js frontend on Heroku. Despite numerous attempts and different configurations, my builds consistently fail due to module resolution errors. Application Infor ...

Unable to delete event listeners from the browser's Document Object Model

Issue at hand involves two methods; one for initializing event listeners and the other for deleting them. Upon deletion, successful messages in the console confirm removal from the component's listener array. However, post-deletion, interactions with ...

Can Firebase functions interact with the file system on Firebase Hosting?

Is it feasible with firebase functions to manipulate the filesystem of firebase hosting? I'm looking to run a build script within the hosting's files using a cloud function. For example, I want to trigger the build script for a Vue application ...

To ensure optimal performance, it is necessary to import the vite build styles individually

I created a vue3+vite package and now I am looking to publish it on npm. However, when I import it into a test project, I find myself having to separately import styles from the dist folder in addition to the package itself. My goal is for the styles to be ...

Attempting to showcase data retrieved from various API calls

I am currently facing an issue where I am retrieving stock/share names from my MongoDB database and attempting to display their prices by making API calls for each of them in my component. However, I am only receiving the price for the last stock. Below i ...

Exploring ways to ensure robust typing for the body of NextApiRequest within a Next.js environment

Are you trying to figure out how to correctly define the body type of an API POST route in Next.js for better type safety? In NextApiRequest, the body is currently defined as "any" and NextApiRequest itself is not generic. I have tried forcefully assigni ...

Utilize the object's ID to filter and display data based on specified criteria

I retrieved an array of objects from a database and am seeking to narrow down the results based on specific criteria. For instance, I want to display results only if a user's id matches the page's correct id. TS - async getResultsForId() { ...

I am experiencing an issue where the Axios configuration does not display the OnUploadProgress on my response

I have been attempting to track the progress of file uploads from the front end, but I am encountering an issue where the onUploadProgress is not being received in the configuration catch. This problem arises as I am relatively new to using Axios. axios({ ...

Retrieve objects from an array that contain a certain specified key

I am trying to extract the objects from All_reports that contain the key: comentarioAdmin. Currently, I am retrieving all reports from All_reports, but I only want the reports that have the key comentarioAdmin. Thank you! getReports() { this.Service.g ...

Uploading Boolean Values from Switch Input (React/Typescript)

I'm facing an issue while trying to post the state value of a switch input toggle control. Whenever I use the submitRecommendation() function through a button click, I encounter a JSON parse error: Cannot deserialize instance of `boolean` out of START ...

Refreshing the resource index view in Laravel Nova

I'm currently working on developing my very first Nova field. This particular index field contains a button that triggers an Axios request. When the response is received, I need to reload the index view. Here's what I have so far: this.$router. ...

How can I implement a user notification service using rxjs within Angular?

As a newcomer to reactive programming, I am exploring ways to create an Angular service that can present notifications to the user. Check out what I have accomplished so far: https://stackblitz.com/edit/angular-rxjs-notifications?file=app%2Fapp.component. ...