A guide to accessing real-time data in Vue.js

This is my debut project in Vue, and I am currently retrieving cart data from the server. My goal is to be able to modify the quantity using Vue. Right now, when I click on the up or down arrow to change the quantity, it gets reflected in the server database. However, I have to reload the page to see the visual change in the UI, which is not what I desire.

I'm looking for a way to instantly visualize the quantity change without having to reload the page once the button is clicked. Additionally, I want the TotalCartPrice method to run automatically without requiring any button clicks. When I open the cart, it should be executed right away. What am I missing?

cart.vue

<template>
    <CartItem v-for="cart in carts" :key="cart.id" :carts="cart" />
</template>
<script>
import CartItem from "../components/cart/cartItem";
export default {
  name: "CartPage",
  components: {
    CartItem
  },
  computed: {
    ...mapGetters(["carts"])
  },
  created() {},
  methods: {
    TotalCartPrice() {
      var total = 0;
      for (var i = 0; i < this.carts.length; i++) {
        total += this.carts[i].product.price * this.carts[i].quantity;
      }
      return total;
    }
  }
};

CartItem.vue

<template>
  <div>
     <h5>${{ carts.product.price }}</h5>
     <div class="product_count">
        <input
          disabled
          name="qty"
          maxlength="12"
          :value="carts.quantity"
          class="input-text qty"
        />
        <button
          @click="addProduct()"
          class="increase items-count"
          type="button"
        >
          <i class="lnr lnr-chevron-up"></i>
        </button>
        <button
          @click="removeProduct()"
          class="reduced items-count"
          type="button"
        >
          <i class="lnr lnr-chevron-down"></i>
        </button>
      </div>
</div>
</template>
<script>
export default {
  name: "cartItem",
  props: {
    carts: {
      required: true,
      type: Object
    }
  },
  data() {
    return {
      cartDetail: {
        product: this.carts.product.id,
        quantity: null,
        customer: null,
        checkout: false
      }
    };
  },
  computed: {
    ...mapGetters(["authUser"])
  },
  methods: {
    ...mapActions(["addTocart"]),
    addProduct() {
      this.cartDetail.quantity = 1;
      this.cartDetail.customer = this.authUser.id;
      this.addTocart(this.cartDetail);
    },
    removeProduct() {
      this.cartDetail.quantity = -1;
      this.cartDetail.customer = this.authUser.id;
      this.addTocart(this.cartDetail)
    }
  }
};
</script>

Cart.js

const state = {
  carts: []
};
const getters = {
  carts: state => state.carts
};
const actions = {
  async addTocart({ commit }, data) {
    const JsonData = JSON.parse(JSON.stringify(data));
    const response = await axios.post("/api/v1/cart/view-set/", JsonData);
    return response;
  },
  async cart({ commit }, data) {
    if (data !== "null") {
      const response = await axios.get(`/api/v1/cart/cartdetial/${data}`);
      commit("setCarts", response.data);
      return response;
    }
  }
};
const mutations = {
  setCarts: (state, carts) => {
    state.carts = carts;
  }
};

export default {
  state,
  getters,
  actions,
  mutations
};

Answer №1

CalculateTotalCartPrice should be transformed into a computed property:

    CalculateTotalCartPrice: function() {
      var cartTotal = 0;
      for (var index = 0; index < this.cartItems.length; index++) {
        cartTotal += this.cartItems[index].item.price * this.cartItems[index].quantity;
      }
      return cartTotal;
    }

Referencing the documentation on differentiating between computed properties and methods:

...computed properties are stored in cache based on their reactive dependencies. A computed property will solely recompute upon changes to its reactive dependencies. Hence, if there is no change in message, successive access to reversedMessage computed property will instantly yield the previously obtained result without rerunning the function.

By employing this approach, your cart price will automatically update whenever this.cartItems undergoes modifications.

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 modify the zAxis of a Paper component in Material-UI?`

Hello, I am curious about how to change the z-axis of a paper from MUI. https://i.sstatic.net/iKXLG.jpg The issue I'm facing is that the carousel is overlapping my menu and I need the menu to be on top of everything. Here is how I have it structure ...

Ways to dynamically retrieve a key value pair in JavaScript and React

I am currently working with a spreadsheet element where the cell values are stored in an object structure like this: localCells = {A1: {input: 'hi', value: 'world'}, A2: {input:'how', value:'you?'}} The object is q ...

Tips on minimizing object array and extracting its worth using javascript

I am currently facing a challenge with reducing an object array. The array is as follows: arr=[{title: 'AP', CurrentDate: 2019-07-31, Status: 'done', NoOfEvents:'6' }] My goal is to reduce this array object specifically to ex ...

I could really use some assistance with this script I'm working on that involves using ($

Using Ajax for Form Submission: $.ajax({ url: 'process.php', type: 'post', data: 'loginName=' + $("#loginName").val() + 'loginPass=' + $("#loginPass").val(), dataType: 'json', success: func ...

Material UI Input Field, Present Cursor Location

Is there a way to retrieve the current cursor (caret) position in a MaterialUI text field? https://material-ui.com/components/text-fields/ I am looking to make changes to the string content at a specific index, such as inserting a character X between cha ...

Displaying Real-Time Values in ReactJS

Hi there, I am currently using the code below to upload images to Cloudinary: import React, { Component } from 'react'; import './App.css'; import Dropzone from 'react-dropzone'; import axios from 'axios'; const F ...

How can we efficiently execute text searches on a large scale by utilizing static index files that are easily accessible online

Looking for a lightweight, yet scalable solution for implementing a full text search index in JavaScript using static files accessible via HTTP? Seeking to make about 100k documents searchable online without breaking the bank on hosting costs like Elastics ...

What is the best method to retrieve JSON data from a different domain?

I am exploring the Google Images API and need to retrieve JSON data from an external domain. In the past, I have used the ajax function to fetch JSON from my own server. However, this time I will be retrieving it from: https://ajax.googleapis.com/ajax/ser ...

Utilizing Jquery for precise element placement and retrieving its position details

Within my bundle of jQuery code, there are a few areas where I am experiencing difficulties trying to recall functions. The following is an excerpt of the code: $(document).ready(function(){ $("#myTablePager").html(""); $.ajax({ type: "POS ...

Updating values within an ng-template can be achieved by accessing and modifying the

I have come across this specific template <script type="text/ng-template" id="template"> <span class="count-container"> <span >{{count}}</span> </span> </script> and it is being included multiple times ...

It is impossible to add a new element between two existing elements that share the same parent

I'm attempting to place an <hr> tag between the first and second .field-container. Because they have the same parent, I thought using element1.parentNode.insertBefore(element2, ...) would be the solution. However, it is not working as expected a ...

The element fails to receive the class when it is being clicked

Currently, I am in the process of developing a Joomla website and I am working on implementing an accordion feature for the category descriptions based on the placement of H3 headings in the WYSIWYG editor. Here is the basic function I have so far (althou ...

Error: Unable to access the 'number' property of an undefined value

How can I use Axios to delete a book from my list? I've tried using the URL of my database along with the id, but it seems like the id is not specified in the URL and remains undefined. This is what my code looks like: export default class ListBooks ...

What causes images to be omitted from a PDF file when using mywindow.print()?

Here is the scenario I am dealing with: On a particular webpage, there is a print button. The page contains various information, including receipts. When the user clicks on "print", I want only the receipts to be printed: https://i.sstatic.net/WobKK.png ...

Issues arise with the functionality of custom jQuery sliders

I'm attempting to create a bootstrap panel slider using my own jQuery code, but it's not functioning as anticipated. My Objective: I have two links for "previous" and "next", and three panels with distinct headings. When the "previous" link is ...

Tips on concealing a div until the value of a specific field surpasses zero

In order to ensure that users focus on the first section of the form before proceeding, I plan to hide the last section until a specific field has a value greater than zero. Check out my HTML code below: <div class="fieldcontainer"> <label>E- ...

The computer system encountered an issue in computing the values of the text

Possible Duplicate: Unable to get textfield value using jQuery My current project involves updating input fields based on user changes in quantity for items. Each item is retrieved from a database and I am generating invoices for customers. However, ...

Strategies for managing large numbers within WebGL GLSL shader programs

What is the best approach to handle large numbers like the one provided in GLSL? I have a shader that requires Date.now() as a uniform, which is defined as: The Date.now() method returns the number of milliseconds elapsed since January 1, 1970 00:00:00 ...

Convert the 'value' attribute in HTML into a clickable link

Is there a way to make the output value of an HTML input field into a clickable link? Right now, it appears as follows: <input type="email" class="form-control" name="contactEmail" value="<?php echo $row_rsContactD ...

Implementing a constant loop repeatedly in NextJs

I am seeking assistance with printing the <Icon /> 700 times on a single page. As a newcomer to NextJs, I have successfully used a for loop to console.log the icons but am unsure of how to actually display them. Any help would be greatly appreciated. ...