How can you connect a property to the output of a method in Vue.js when working with TypeScript and vue-property-decorator?

I'm working with a TypeScript single file vue component. I've encountered an issue where the template does not display the values returned by certain component methods.

Here's a snippet of the template:

<div class="order-items">
    <div class="order-item" v-for="(item, itemIndex) in order.items">
        <img class="order-item-icon" :src="getIcon(item.name)" />
        <span class="order-item-name">{{ itemsList[item.name].name }}</span>
        <span class="order-item-amount">{{ getPlayerAmount(item.name) }}/{{ item.amount }}</span>
    </div>
</div>

In the script section, there are a couple of methods being used. I am utilizing vue-property-decorator:

@Emit() getPlayerAmount(itemName: string): string {
    if (this.inventory[itemName]) {
        return `'${this.inventory[itemName].amount}'`;
    } else {
        return '0';
    }
}

@Emit() getIcon(itemName: string): string {
    const icon = Items.getItemData(itemName).icon;
    return icon;
}

Although these methods are being called correctly and returning the expected values, the template is not displaying them as intended. The order-item-icon image tag lacks the src attribute, and the order-item-amount span is missing information before the '/' symbol.

Is there a specific step that needs to be taken for binding properties to component methods?

Answer №1

When the Emit decorator is used, the method's return Vue is checked to determine if the event should be emitted or not (source).

In simpler terms, methods annotated with Emit will always yield a value of undefined (reference).

Solution: Simply remove the decorator and manually emit the events.

The following snippets demonstrate the alternative approach:

getPlayerAmount(itemName: string): string {
    this.$emit('get-player-amount', itemName);
    if (this.inventory[itemName]) {
        return `'${this.inventory[itemName].amount}'`;
    } else {
        return '0';
    }
}

getIcon(itemName: string): string {
    const icon = Items.getItemData(itemName).icon;
    if (icon) this.$emit('get-icon', itemName);
    return icon;
}

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

Is there a way to verify if the object's ID within an array matches?

I am looking to compare the ID of an object with all IDs of the objects in an array. There is a button that allows me to add a dish to the orders array. If the dish does not already exist in the array, it gets added. However, if the dish already exists, I ...

Better ways to conceal notifications as soon as a new one appears with Toastr

Whenever a new notification pops up in my application, I desire for the previous one to automatically disappear. It is crucial for only one notification to be displayed at any given time. Is there a way to accomplish this using toastr? ...

Guide to implementing Apollo GraphQL subscriptions in NextJS on the client-side

As a newcomer to NextJS, I am facing the challenge of displaying real-time data fetched from a Hasura GraphQL backend on a page. In previous non-NextJS applications, I successfully utilized GraphQL subscriptions with the Apollo client library which levera ...

Ways to control the number of boxes that are checked

I am currently working on a script to restrict the number of checkboxes that can be checked, but I am encountering an issue where the script is disabling all checkboxes on the page. Is there a way to only disable a specific checkbox within a certain div? ...

Error: Incorrect data type found in React Route component

I've encountered an issue while attempting to utilize the Route component in my application. The error message I'm receiving reads as follows: [ts] Type '{ path: "/:shortname"; component: typeof FirstComponent; }' is not assignable ...

Separating the time and date into distinct variables offers flexibility in how they

Struggling with formatting time in a web component using TypeScript and React. The code below is working: new Date(myDate) .toLocaleTimeString( 'en-US', { weekday: 'short', year: 'numeric', month: 'short', ...

Modify the color scheme of an HTML webpage

Looking to enhance my HTML page with a new feature. The page is responsive and currently using Bootstrap CSS and JS. My goal is to allow users to change the color of the page dynamically by selecting a background or text color. Check out this example link ...

Harnessing the power of two-way data binding in VueJS

I am looking to utilize Vue's two-way data binding to dynamically update the values of amount and total. The price of a given product is fixed. When users modify the amount, the total = amount * total will be automatically calculated. Similarly, users ...

Encountering difficulties while attempting to import a module in Next.js

My attempt to import the Zoom Web SDK module into my Next.js project encountered an error due to the undefined window object. Simply trying to import the websdk module resulted in this unexpected issue https://i.stack.imgur.com/NDRoC.png I am using Next ...

Encountering difficulties with managing the submit button within a ReactJS form

As I work on creating a User registration form using React JS, I encounter an issue where the console does not log "Hello World" after clicking the submit button. Despite defining the fields, validations, and the submit handler, the functionality seems to ...

Dexie is alerting us to a problem with a call that occurs before initialization

When setting up my application, I encountered an error related to the Courses Entity Class being called before initialization in my Dexie Database. Despite checking my code, I couldn't find any issues and there was no documentation available for this ...

Tips for organizing a search using two keys in Javascript

I am dealing with a large dataset containing over ten thousand objects that hold information about two different ids as shown below: dataSet = [ { ids: ["123", "234"], information: 1 }, { ids: ["123", "345"], in ...

What sets Observables (Rx.js) apart from ES2015 generators?

From what I've gathered, there are various techniques used for solving asynchronous programming workflows: Callbacks (CSP) Promises Newer methods include: Rx.js Observables (or mostjs, bacon.js, xstream etc) ES6 generators Async/Await The trend ...

Using Angular 6 HttpClient to retrieve an object of a specific class

Previously, we were able to validate objects returned from http api calls using the instanceof keyword in Angular. However, with the introduction of the new HttpClient Module, this method no longer works. I have tried various simple methods, but the type c ...

Tips for resolving the problem of Google Maps repeatedly appearing when utilizing the Auto-Loading feature

I need help understanding the issue that arose when loading the Google Maps API. "You have included the Google Maps API multiple times on this page. This may cause unexpected errors." This error occurred while attempting to automatically load the API. B ...

What is the best way to apply a mask to a textbox to format the date as MM/yyyy using a mask

In my asp.net application, I have a TextBox for entering Credit card date (month & year only). I tried using the 'TextBox with masked edit extender' and set Mask="99/9999" with Mask Type="Date. However, it is not working as expected - it only wor ...

Leveraging the replace feature within Selenium IDE

After extracting information from a webpage, I found a string that read "price: $30.00" which I saved as "x." What I really needed was just the numbers - "30.00". I attempted to use x.replace(), but unfortunately it didn't work out. If anyone could as ...

How can I configure a mocked dependency in Jest to return a specific value in a function?

I am currently working on simulating a mongoose model to facilitate unit testing for an express controller. To keep things simple, I've removed all unnecessary code and provided below the specific scenario I'm dealing with. Here's the snippe ...

Check if a value is present in the array with *ngIf

I'm curious about how to use the ngIf directive in a specific scenario. In my Angular application, I have dynamically generated angular material toggles, each with a unique id. I'm familiar with using ngIf to conditionally display elements on the ...