Calculating discounts using Vue.js: A step-by-step guide

I am working with a basic database that contains several fields including id, product_name, original_price, and discount. The discount field is specified in percentage format. To populate all the data at once using Axios and display it on the page using v-for I have utilized the following code:

<ul v-for="product in products">
   <li>@{{product.product_name}}</li>
   <li>@{{product.original_price}}</li>
   <li>@{{product.discount}}</li>
</ul>

Now, I am looking to show the calculated price after applying the discount. To achieve this, I am considering creating a method in my Vue instance as shown below:

      calculateDiscount: function(orig_price, discount){
                         this.discount_amt = discount/100*orig_price;
                         return this.after_discount = orig_price - this.discount_amt;
    }

If I implement this method, how can I invoke it during rendering? Any assistance would be greatly appreciated.

Answer №1

Instead of using a computed property which cannot take any parameters, you can utilize a method to perform calculations on each product in the products array.

<ul v-for="product in products">
  <li>@{{product.product_name}}</li>
  <li>@{{product.original_price}}</li>
  <li>@{{product.discount}}</li>
  <li>@{{ discountedPrice(product) }}</li>
</ul>


methods: {
  discountedPrice(product) {
    return product.original_price - (product.original_price *(product.discount)/100)
  }
}

Answer №2

Perform the calculation on your server side and set the after_discount value as the final discount for each product. You can then display the discount using the following code snippet.


   <ul v-for="product in products">
       <li>@{{product.product_name}}</li>
       <li>@{{product.original_price}}</li>
       <li>@{{product.discount}}</li>
       <li>@{{product.after_discount}}</li>
   </ul>

I hope this information is useful to you.

Answer №3

Utilize the filter functionality in Vue.js

var app = new Vue({
  el: '#app',
  data () {
    return {
      list: [{
        product_name: 'Shoes',
        original_price: 300,
        discount: 8.5
      },{
        product_name: 'Jacket',
        original_price: 1200,
        discount: 7.5
      },{
        product_name: 'Hat',
        original_price: 3000,
        discount: 5.5
      }]
    }
  },
  filters: {
    priceAfterDiscount (v,discount) {
      return (v * discount / 10).toFixed(2);
    }
  }
})
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<div id="app">
    <ul v-for="item of list">
      <li>Product: {{item.product_name}}</li>
      <li>Price: ${{item.original_price}}</li>
      <li>Discount: {{item.discount}}%</li>
      <li>Price After Discount: ${{item.original_price | priceAfterDiscount(item.discount)}}</li>
    </ul>
</div>

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

How can I retrieve the parent scope in an Angular UI nested named view?

One of the challenges I faced in my application was dealing with nested views within several screens. After experimenting with different approaches, I discovered that creating modal dialog boxes and sliding panels as actual nested states with corresponding ...

Error: The React Hook "useX" should not be invoked at the top level of the code

I am facing a challenge while attempting to transfer the exception handling logic from the component to my service class: Login.tsx: import { useSnackbar } from "notistack"; // ... const Login = () => { const { enqueueSnackbar } = useSnack ...

The anchor events in the DataTable are not responding when clicked, resulting in a failure to load resources

When it comes to jQuery event delegation using on() and live() functions, I have encountered a problem. I am trying to create a function that triggers when a user clicks on an element in a dataTable. Can anyone help me figure out what's going wrong? I ...

Setting Authorization with username, password, and domain in Angular 2 HTTP Request

I am facing an issue with calling an API method hosted on another machine using Angular 2 component with Http. When accessing the API from a browser, I can connect by entering a username and password as shown below: https://i.stack.imgur.com/JJqpC.png Ho ...

Launch a "mini" web browser from Outlook

My upcoming project involves creating an Outlook add-in where users can open a browser window by clicking a button to fill out necessary forms via a specific URL. While I know opening a browser from Outlook is possible, I am concerned that the entire brow ...

Struggling to render the template inside a .vue file in a Vue.js + TypeScript project?

Is anyone familiar with setting up a Vue TS based project? I have encountered an issue where the template data is not being rendered in the browser's DOM. The project structure can be found in this repository: https://github.com/AndrewBogdanovTSS/typ ...

"Looping through elements with ng-repeat does not seem to refresh

Currently, I am working on implementing a drag and drop ranking question using Angular. The functionality is working smoothly, except for one issue in Chrome where the labels for the ranking question do not update properly. To demonstrate the problem, I h ...

jQuery show/hide function malfunctioning

Currently, I am attempting to create a basic show/hide interaction for a div using jQuery. The goal is to make the artists-home div vanish and be replaced by the .ken-gallery when the .artist-ken is clicked. Here is my current code, although it is not fun ...

Switching video sources with jQuery and HTML5 can be achieved by clicking on an

I need to develop an engaging video using HTML5 and jQuery. My objective is to: Start playing video1 Show button1 when video1 finishes, then switch to video2 upon clicking and hide button1 Play video2 Display button 2 after video2 ends, then change to vi ...

What could be causing the error message "userID is not defined" to appear?

Can someone assist me with this script issue? I keep receiving the error message "userID is not defined." I'm attempting to bulk modify licenses following a tutorial on https://www.youtube.com/watch?v=e4KTAytOeyA function updateLicenses() { var u ...

Picture cannot reemerge with SetTimeout

Browsing Experience: Users will simply tap on an image (group of spots) to make it disappear from the screen. Upon clicking the image, it will smoothly fade out. However, if the user does not interact with the image, a new one won't show up after 10 ...

Exploring the functionality of uiRouter using the requirejs framework

I've been struggling with a problem for a while now and haven't found any solutions in other posts related to testing uiRouter with requirejs. I have a basic controller set up that uses $state.go to switch states when a button is clicked. runsCo ...

Load JavaScript only when the lightbox appears

Every page on my website has a button that, when clicked, opens a lightbox. Inside the lightbox is a form that requires JavaScript files, specifically Angular. These JavaScript files are exclusive to the form and not used elsewhere on the site. To improve ...

Using Jquery Chosen Plugin to Dynamically Populate One Chosen Selection Based on Another

Good evening to all, please excuse any errors in my English. I have successfully integrated a jQuery Chosen plugin with my 'estado' field (or province). My goal is to populate another jQuery Chosen plugin with the cities corresponding to that s ...

Unable to add information to data property in Vue.js

I am working on creating an array of objects called hourlyTemperatureData by looping through all the items in weatherData.hourly and filtering some data. The structure of the expected data within hourlyTemperatureData should be like - {'abc':123 ...

Error 404 encountered while attempting to GET on a socket.io server within a Django template

Currently, I am experimenting with integrating Socket.io and Django within a project. However, I encountered an issue when loading the socket.io script from the server. <script src="localhost:3000/socket.io/socket.io.js"></script> <script&g ...

Is there a way to trim the current shapes in three.js?

I have created a shape similar to this using Box Geometry at the following link: https://jsfiddle.net/cdu96z3c/. I am looking to achieve a design like the image below by properly utilizing v.x and v.z, while maintaining the current corrugation and properti ...

Ways to showcase Switch/Case in two separate drop-down menus

I'm currently working on a PHP file with a switch/case structure that I believe is in JSON format. While I may not be an expert in PHP, AJAX, and JSON, I'm really putting effort to learn more about it. <?php switch($_GET['make'] ...

The organizational structure of data in MongoDB for posts, comments, saved content, and likes

I am currently diving into the world of MEANJS web development and working on structuring my data. As a newcomer to the NoSql concept, I am seeking guidance on the best practices to follow. The data I need to store includes: questions answers likes saved ...

Apply active class to a link element in React JS

Creating a component that displays menus from an array import React from 'react' import { Link, browserHistory,IndexLink } from 'react-router' $( document ).ready(function() { $( "ul.tabs li a" ).first().addClass("current"); ...