I want to use an external JS function into a vue file.
Js file contains the method:
let calculateDiscount = {
PriceAfterDiscount(price, discountPercentage) {
const discountAmount = (discountPercentage * price) / 100;
return price - discountAmount;
}
};
export default calculateDiscount;
Vue file
<template>
<div v-for="product in product_data" :key="product.id">
<h4> ${{ Discount(product.price, product.sale) }}</h4>
</div>
</template>
<script>
import CalculateDiscount from "@/utilities/CalculateDiscount"; //js file containing the method
name: "ShowProduct",
methods: {
Discount(){
CalculateDiscount.PriceAfterDiscount();
}
}
</script>
I far I guess I can't import the function in method property in the right manner. Can anyone help me? Thanks in advance.
2 Answers 2
You need to update calculateDiscount object like:
let calculateDiscount = {
PriceAfterDiscount: (price, discountPercentage) => {
const discountAmount = (discountPercentage * price) / 100;
return price - discountAmount;
}
};
and then CalculateDiscount.PriceAfterDiscount(); should work fine.
In the template, you had called Discount function with two params like:
{{Discount(product.price,product.sale)}}
but in actual code you had passed nothing:
methods: {
Discount() {
calculateDiscount.PriceAfterDiscount();
}
}
Also, you have passed nothing to calculateDiscount.PriceAfterDiscount(). You need the pass the values from template to this and also return the result, otherwise it will never print nothing in UI:
methods: {
Discount(price, sale) {
return calculateDiscount.PriceAfterDiscount(price, sale);
}
}
6 Comments
calculateDiscount or PriceAfterDiscount is not declare anywhere or used anywhere?Discount function with two params like Discount(product.price,product.sale) but in actually code you had passed nothing methods: { Discount() {. Also, you have to return the calculateDiscount.PriceAfterDiscount() result otherwise it will never print anything in UI. Updated Demo JavaScript modules work as namespaces and don't need additional object literal or class to be wrapped around exports.
PriceAfterDiscount doesn't rely on calculateDiscount members and doesn't need to be defined as a part of it.
It can be:
export function PriceAfterDiscount(price, discountPercentage) {
const discountAmount = (discountPercentage * price) / 100;
return price - discountAmount;
}
};
And imported like:
import { PriceAfterDiscount } from "@/utilities/CalculateDiscount";
PriceAfterDiscount(...);
Or if it needs a namespace:
import * as calculateDiscount from "@/utilities/CalculateDiscount";
calculateDiscount.PriceAfterDiscount(...);