Troubleshooting Vue and Typescript: Understanding why my computed property is not refreshing the view

I'm struggling to understand why my computed property isn't updating the view as expected. The computed property is meant to calculate the total price of my items by combining their individual prices, but it's only showing me the initial price.

I have an

<input type="number" min="1" v-model.number="count" />
field that, when multiplied with the item price, should give me the total combined price. After some investigation, I suspect that the issue lies within this input field, however, I'm unsure how to resolve it. Could someone assist me in fixing this bug?

<template>
  <main class="container">
    <section
      class="image"
      :style="`background: url(/${currentItem.img}) no-repeat center center`"
    ></section>

    <section class="details">
      <h1>{{ currentItem.item }}</h1>

      <h3>Price: ${{ currentItem.price.toFixed(2) }}</h3>

      <div class="quantity">
        <input type="number" min="1" v-model.number="count" />
        <button @click="addToCart" class="primary">
          Add to Cart - ${{ combinedPrice }}
        </button>
      </div>
      {{ combinedPrice }}
      <fieldset v-if="currentItem.options">
        <legend>
          <h3>Options</h3>
        </legend>
        <div v-for="option in currentItem.options" :key="option">
          <input
            type="radio"
            name="option"
            :id="option"
            :value="option"
            v-model="itemOptions"
          />
          <label :for="option">{{ option }}</label>
        </div>
      </fieldset>

      <fieldset v-if="currentItem.addOns">
        <legend>
          <h3>Add Ons</h3>
        </legend>
        <div v-for="addon in currentItem.addOns" :key="addon">
          <input
            type="checkbox"
            name="addon"
            :id="addon"
            :value="addon"
            v-model="itemAddons"
          />
          <label :for="addon">{{ addon }}</label>
        </div>
      </fieldset>
      
    </section>

    <section class="options">
      <h3>Description</h3>
      <p>{{ currentItem.description }}</p>
    </section>
  </main>
</template>

<script lang="ts">
import Vue from "vue";
import { mapState } from "vuex";
import { Item } from "@/api/interfaces";

export default Vue.extend({
  data() {
    return {
      id: this.$route.params.id,
      count: 1,
      itemOptions: "",
      itemAddons: [],
      itemSizeAndCost: [],
      cartSubmitted: false,
    };
  },
  computed: {
    ...mapState(["foodData"]),
    currentItem(): Item {
      let result;
      for (let i = 0; i < this.foodData.length; i++) {
        for (let j = 0; j < this.foodData[i].menu.length; j++) {
          if (this.foodData[i].menu[j].id === this.id) {
            result = this.foodData[i].menu[j];
            break;
          }
        }
      }
      return result;
    },
    combinedPrice(): number {
      let total = this.count * this.currentItem.price;
      return total;
    },
  },
});
</script>

Upon inspecting the Chrome Vue Extension, I can see that the count and combinedPrice are being updated correctly

https://i.stack.imgur.com/eWCCu.png

Answer №1

The issue arose because the button was not properly handling a method. The function of the button relied on a computed property, but once a specific method was implemented, everything worked seamlessly.

<button @click="addToCart" class="primary">
          Add to Cart - ${{ combinedPrice.toFixed(2) }}
        </button>

 methods: {
    addToCart() {
      alert("add to cart button");
    },
  },

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

What is the best way to initiate a change when adding a new property to an object in VueJs?

Here is the initial structure of my vuex state in a VueJS project: state: { level1prop: null } After dynamically changing and mutating it, the structure becomes: state: { level1prop: { level2prop: { level3prop: { ...

Webpack focuses solely on serving HTML files, neglecting to deliver the underlying code

Hey there! I'm currently working on a project that involves using React, TypeScript, and Webpack. I ran into some errors previously that prevented the code from compiling, but now that's fixed. However, when I run webpack, it only serves the HTML ...

I'm encountering an issue with my array in JavaScript while using // @ts-check in VS Code. Why am I receiving an error stating that property 'find' does not exist on my array? (typescript 2.7

** update console.log(Array.isArray(primaryNumberFemales)); // true and I export it with: export { primaryNumberFemales, }; ** end update I possess an array (which is indeed a type of object) that is structured in the following manner: const primar ...

The prolonged action is causing the renderer process to become locked

I am currently experiencing an issue with a function that is triggered by changes in a vue-select component within my component template. <v-select v-model="model" :options="eventList" :placeholder="currentEventTitle" v-on:input="selectedEvent" ...

What is the best way to update the displayed data when using Mobx with an observable array?

Is there a way to re-render observable array data in Mobx? I have used the observer decorator in this class. interface IQuiz { quizProg: TypeQuizProg; qidx: number; state: IStateCtx; actions: IActionsCtx; } @observer class Comp extends Rea ...

Anticipate that the function parameter will correspond to a key within an object containing variable properties

As I develop a multi-language application, my goal is to create a strict and simple typing system. The code that I am currently using is as follows: //=== Inside my Hook: ===// interface ITranslation { [key:string]:[string, string] } const useTranslato ...

Discovering the interface type of class properties in order to implement a factory method

I am struggling with implementing a factory method in my code. I want to be able to pass not only a Class type to instantiate but also a set of default values for the properties within the class. My goal is to have the compiler notify me if I try to pass i ...

A technique for calculating the total quantity of each item individually while using v-for in VueJS

Struggling to code (complete newbie) using VueJS and facing a major roadblock. I have a list of orders and I need to sum the quantities of each item separately. The only way to access the items is through v-for. <tr> <td data-th="list"> < ...

Ways to verify the authenticity of a JWT token

I recently came across a tutorial on creating user authentication with Vue.js and Lumen. The tutorial utilizes the tymon/jwt-auth library to handle authentication. So far, everything is working smoothly. The API manages all my data and provides a token to ...

Issue with authentication and cross-origin resource sharing (CORS) when implementing Spring Boot, Spring Security, Vue.js,

Running on vue.js 3, Vite 4.0.2, axios 0.25.0, and spring boot (Starter 2.7.2). A backend has been created in spring boot while using vue.js3, vite, and axios for the UI. Now, I simply want to make a call to rest with axios. Before implementing these func ...

Vue function displays 'undefined' message

Although many posts on this topic exist already, I am struggling to understand what is going wrong (even after searching extensively here and on Google). I have created my interceptor like this, but I keep receiving an error message stating "This is undef ...

Are the frameworks Vue, Angular, and React known for

During a conversation, I came across an interesting viewpoint criticizing popular frameworks such as Angular, Vue, and React. It was argued that these frameworks have a significant disadvantage: apart from the API part that interacts with the server's ...

Testing vue.js components through vue-loader with dependency injection

I am currently experimenting with testing my Vue.js component using vue-loader, a webpack loader. I tried following the tutorial provided by vue-loader but encountered unexpected issues. Below is the code snippet for my component: <template> <h ...

Switch out an item within a list of objects with a different item

I have a variable called this.rows that contains a collection of items. There is a real-time item being received from the server, which matches one of the items in the this.rows object collection. How can I replace an item with new values? Below is an ex ...

Achieving reactivity in Vue when pushing elements into a dynamically-sized array

I am in need of a two-dimensional array that can have dynamic keys and an array of objects pushed to it. I have tried using this.$set and Vue.set without any success so far. data() { rep_recs: [] , // I want this array to be reactive so that I can displ ...

React Typescript is causing issues with the paths not functioning properly

Looking to simplify my import paths and remove the need for deeply nested paths. Currently working with React and TypeScript, I made adjustments to my tsConfig file like so: { "compilerOptions": { "baseUrl": "src", & ...

Using identical content in various template slots

Is it possible in vuejs to assign the same content to multiple slots without repeating it? For example: <base-layout> <template slot="option"> <span :class="'flag-icon-' props.option.toLowerCase()" />{{ countriesByCode ...

Unit testing in Angular 2+ involves testing a directive that has been provided with an injected window object

Currently, I am faced with the challenge of creating a test for a directive that requires a window object to be passed into its constructor. This is the code snippet for the directive: import { Directive, ElementRef, Input, OnChanges, OnDestroy, OnInit ...

Utilizing numerical values in useParams - A beginner's guide

Trying to access specific data from my json file using an ID, like "http://localhost:3001/pokemons/3", leads to a 404 error. All the data is visible at http://localhost:3001/pokemons. It seems that useParams doesn't want me to use id as a number - q ...

What is the best way to transfer the API Response Time from one Fetch function to a separate asynchronous function?

After successfully obtaining the API Response Time (duration) using the 'makeAPICall' function, I am now faced with the task of passing this duration variable value to another asynchronous function. Can anyone assist me in finding a solution to a ...