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
};