Этот Vue-компонент отображает корзину товаров с возможностью динамического изменения количества товаров через AJAX-запросы к компоненту Битрикса, с мгновенным пересчетом общей суммы.
| Код |
|---|
<?php
// /local/components/my/cart/templates/.default/template.php
if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true) die();
use Bitrix\Main\Web\Json;
$this->setFrameMode(true);
?>
<div id="vue-cart" data-props='<?= Json::encode($arResult['CART_DATA']) ?>'></div>
<script>
document.addEventListener('DOMContentLoaded', function() {
const { createApp } = window.Vue;
createApp({
data() {
return {
items: [],
loading: false
}
},
computed: {
total() {
return this.items.reduce((sum, item) => sum + (item.PRICE * item.QUANTITY), 0);
}
},
mounted() {
const props = JSON.parse(document.getElementById('vue-cart').dataset.props);
this.items = props.items || [];
},
methods: {
async updateQuantity(itemId, newQuantity) {
this.loading = true;
try {
const result = await BX.ajax.runComponentAction('my:cart', 'update', {
mode: 'class',
data: { itemId, quantity: newQuantity }
});
this.items = result.data.cart;
} catch (error) {
console.error('Ошибка обновления:', error);
}
this.loading = false;
}
},
template: `
<div class="cart">
<div v-if="loading" class="loading">Обновление...</div>
<div class="cart-item" v-for="item in items" :key="item.ID">
<span>{{ item.NAME }}</span>
<input
type="number"
:value="item.QUANTITY"
@change="updateQuantity(item.ID, $event.target.value)"
min="1">
<span>{{ item.PRICE * item.QUANTITY }} ₽</span>
</div>
<div class="cart-total">Итого: {{ total }} ₽</div>
</div>
`
}).mount('#vue-cart');
});
</script> |