Простого интернет-магазина на Vue с каталогом товаров и корзиной. Этот пример не использует Vuex или внешние библиотеки — только Vue 3
, Composition API
и базовую структуру компонентов.
📁 Структура проекта
simple-shop/
├── index.html
├── main.js
├── App.vue
├── components/
│ ├── ProductList.vue
│ ├── Cart.vue
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Simple Vue Shop</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/main.js"></script>
</body>
</html>
main.js
import { createApp } from 'vue'
import App from './App.vue'
createApp(App).mount('#app')
App.vue
<template>
<div class="container">
<h1>Магазин</h1>
<ProductList :products="products" @add-to-cart="addToCart" />
<Cart :items="cart" @remove-from-cart="removeFromCart" />
</div>
</template>
<script setup>
import { ref } from 'vue'
import ProductList from './components/ProductList.vue'
import Cart from './components/Cart.vue'
const products = ref([
{ id: 1, name: 'Телефон', price: 500 },
{ id: 2, name: 'Ноутбук', price: 1200 },
{ id: 3, name: 'Наушники', price: 150 }
])
const cart = ref([])
function addToCart(product) {
const item = cart.value.find(p => p.id === product.id)
if (item) {
item.quantity++
} else {
cart.value.push({ ...product, quantity: 1 })
}
}
function removeFromCart(productId) {
const index = cart.value.findIndex(p => p.id === productId)
if (index !== -1) {
if (cart.value[index].quantity > 1) {
cart.value[index].quantity--
} else {
cart.value.splice(index, 1)
}
}
}
</script>
<style>
.container {
max-width: 800px;
margin: 0 auto;
font-family: Arial, sans-serif;
}
</style>
components/ProductList.vue
<template>
<div>
<h2>Каталог</h2>
<ul>
<li v-for="product in products" :key="product.id">
{{ product.name }} — {{ product.price }}₽
<button @click="$emit('add-to-cart', product)">Добавить в корзину</button>
</li>
</ul>
</div>
</template>
<script setup>
defineProps(['products'])
defineEmits(['add-to-cart'])
</script>
components/Cart.vue
<template>
<div>
<h2>Корзина</h2>
<p v-if="items.length === 0">Корзина пуста</p>
<ul>
<li v-for="item in items" :key="item.id">
{{ item.name }} x{{ item.quantity }} — {{ item.price * item.quantity }}₽
<button @click="$emit('remove-from-cart', item.id)">Удалить</button>
</li>
</ul>
<p v-if="items.length">Итого: {{ total }}₽</p>
</div>
</template>
<script setup>
import { computed } from 'vue'
const props = defineProps(['items'])
defineEmits(['remove-from-cart'])
const total = computed(() => {
return props.items.reduce((sum, item) => sum + item.price * item.quantity, 0)
})
</script>
✅ Как запустить
-
Создай проект в любом менеджере (например, Vite):
npm create vite@latest simple-shop -- --template vue cd simple-shop npm install npm run dev
-
Замени файлы на те, что выше.
Автор: Евгений Морковин
0 комментариев