Nuxt.js 3 ile bir e-ticaret uygulaması yaptığınızı düşünün, bu uygulamanın sepet işlemlerini de veritabanıyla sık sık veri alışverişi yapmadan hızlıca çözmek istiyorsunuz diyelim. Bunun için kullanılabilecek en uygun iki yöntemden biri olan verileri localstorageda tutarak e-ticaret sepeti oluşturalım. Başlıyoruz..
Yeni bir Nuxt.js 3 projesi oluşturun:
npx create-nuxt-app my-project
Projeyi çalıştırın:
cd my-project
npm run dev
Yeni bir “Sepet” bileşeni oluşturun:
<template>
<div>
<h2>Sepetiniz</h2>
<ul>
<li v-for="product in products" :key="product.id">
{{ product.name }} - {{ product.price }} TL
<button @click="removeProduct(product)">Ürünü Sil</button>
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
products: []
}
},
methods: {
addProduct(product) {
this.products.push(product);
this.saveProducts();
},
removeProduct(product) {
const index = this.products.indexOf(product);
if (index !== -1) {
this.products.splice(index, 1);
this.saveProducts();
}
},
saveProducts() {
localStorage.setItem('products', JSON.stringify(this.products));
},
loadProducts() {
const products = localStorage.getItem('products');
if (products) {
this.products = JSON.parse(products);
}
}
},
mounted() {
this.loadProducts();
}
}
</script>
Bu bileşen, sepete eklenen ürünleri listeler ve “Ürünü Sil” düğmesine tıklandığında ürünü listeden kaldırır.
Ana bileşeninize “Sepet” bileşenini dahil edin:
<template>
<div>
<h1>Ürünler</h1>
<ul>
<li v-for="product in products" :key="product.id">
{{ product.name }} - {{ product.price }} TL
<button @click="addProduct(product)">Sepete Ekle</button>
</li>
</ul>
<Sepet />
</div>
</template>
<script>
import Sepet from '~/components/Sepet.vue';
export default {
components: {
Sepet
},
data() {
return {
products: [
{ id: 1, name: 'Ürün 1', price: 10 },
{ id: 2, name: 'Ürün 2', price: 20 },
{ id: 3, name: 'Ürün 3', price: 30 }
]
}
},
methods: {
addProduct(product) {
this.$refs.sepet.addProduct(product);
}
}
}
</script>
Bu bileşen, ürün listesini ve “Sepete Ekle” düğmesini içerir ve “Sepet” bileşenine veri eklemek için kullanılır.
Projenizi çalıştırın ve ürünleri sepete ekleyin. Eklediğiniz ürünler local storage’da saklanacaktır.
npm run dev
Ürünleri sepete ekleyin ve sayfayı yeniden yükleyin. Sepetteki ürünler hala orada olacak.
Sepeti boşaltmak için “localStorage.clear();” yöntemini kullanabilirsiniz.
clearProducts() {
localStorage.clear();
this.products = [];
}
Bu örnek uygulama, ürünleri bir sepete eklemenize ve bunları local storage’da saklamanıza olanak tanır. Bu sayede sepette yaptığınız her işlem için veritabanıyla haberleşmek zorunda kalmazsınız, dolayısıyla kullanıcı deneyimini iyileştirebilirsiniz. Hepsi bu kadar!
Bir cevap yazın