【问题标题】:How to implement add to cart functionality in ember app如何在 ember 应用中实现添加到购物车功能
【发布时间】:2022-06-10 18:05:34
【问题描述】:

我一直在从事电子商务项目。作为该项目的一部分,我必须实现添加到购物车功能。我的前端是 ember,后端是 rails-api。 我已经使用计算属性来实现这一点,但是数据库中的所有数据都显示在购物车页面中。 如何使用 ember 实现合适的购物车?

Ember 版本是 3.4.4 Rails 版本是 7.0.2.3

// app/services/shopping-cart.js
import Service from '@ember/service';
import { computed } from '@ember/object';
const { service } = Ember.inject;
export default Service.extend({
    session: service('session'),
    store: service('store'),
    currentUser: service('currentUser'),
    itemsIds: [],
    items:computed("itemsIds.[]", function(){
        const itemsIds = this.itemsIds;
        return this.store.query('product', {id: itemsIds.id});
    }),
    addItem(itemId){
        this.itemsIds.addObject(itemId);
    },
    removeItem(itemId){
        this.itemsIds.removeObject(parseInt(itemId));
    }

});

// app/routes/product.js
import Route from '@ember/routing/route';
import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin';
const { service } = Ember.inject;

export default Route.extend(AuthenticatedRouteMixin, {
    session: service('session'),
    currentUser: service('currentUser'),
    
    model(params){
        return this.store.findRecord('product', params.product_id);
    }
    
});

// app/controllers/product.js
import Controller from '@ember/controller';

const { service } = Ember.inject;
export default Controller.extend({
    session: service('session'),
    currentUser: service('currentUser'),
    shoppingCart: service('shoppingCart'),
    quantity: 1,
    price: 0,
    dialogBox: false,
    actions:{
        addToItem(model){
            const id = model.id;
            this.shoppingCart.addItem(id);
        },

        order(){
            var self = this;
            function setPrice(){
                self.set('price', (self.model.price * self.quantity));
            }
            this.set('dialogBox', true);
            const user_id = this.currentUser.user;
            let date = new Date();
            date.setDate(date.getDate() + 2);
            const orders = this.store.createRecord('order',{
                deliveryDate: date,
                processing: true,
                user_id: user_id
            });
            orders.save().then(setPrice());
        },

        orderItem(){
            this.set('dialogBox', false);
            console.log(this.model.id);
            const orderItems = this.store.createRecord('order-item', {
               quantity: this.quantity,
               product_id: this.model,
               price: this.quantity * this.model.price

           })
           orderItems.save().then(function(response){
               alert("Order has been placed successfully!!");
           });
        },

        showDialog(){
            this.set('dialogBox', true);
        },

        hideDialog(){
            this.set('dialogBox', false);
        },
        cancel(){
            
        }
    }
});

{{!-- app/templates/products.hbs --}}
<div class="container mt-5">
    <div class="row">
        <div class="col">
             {{#link-to 'dashboard'class="nav-link"}}<i class="fa-solid fa-arrow-left fa-2x"></i>{{/link-to}}
        </div>
        <div class="col">
            <h1>Product details</h1>
        </div>
        <div class="col">
            {{#link-to 'cart'class="nav-link"}}<i class="fa-solid fa-cart-shopping fa-2x"></i>{{/link-to}}
        </div>
    </div>
    <hr>
    <div class="container">
        <div class="row">
            <div class="col-sm-6">
                <img class="product-image" src="/assests/images/{{this.model.images}}.jpeg" alt="">
            </div>

            <div class="col-sm-6">
                <h1>{{this.model.title}}</h1>
                {{quantity-checker this.model.quantity this.model.price}}
                <button class="btn btn-success" {{action "addToItem" this.model on="click"}} >
                    <i class="fa-solid fa-cart-shopping"></i>
                    <span>Add to Cart</span>
                </button>
                <label class="quantity-label" for="quantity">Quantity Selector:</label>
                {{!-- <input type="number" name="quantity" id="quantity" class="quantity-selector" min="0" value="{{this.quantity}}"> --}}
                {{input type="number" name="quantity" id="quantity" class="quantity-selector" min="0" value=this.quantity}}
            </div>
        </div>
    </div> 
    <hr> 
    <h4> Description</h4>
    <div class="container">
        {{#each this.model.description as |line|}}
            <p>{{line}}</p>
        {{/each}}
        <ul>
        {{description-formatter this.model.description}}
        </ul>
    </div>
    <button class="btn btn-success" {{action "order" this.model  on="click"}}>Order now</button>

</div>

<div class="dialog-container {{if this.dialogBox "show-dialog" "hide-dialog"}}">
    <div class="dialog">
        <h5>{{this.model.title}}</h5>
        <h5>The price is {{this.price}}</h5>
        <h5 class="confirmation">Are you sure, you wanna place this order?</h5>
        <h5>Quantity: {{this.quantity}}</h5>
        <div class="dialog-buttons">
            <button {{action "orderItem"}} class="btn btn-success">
                <i class="fa-solid fa-badge-check"></i>Yes
            </button>
            <button {{action "hideDialog"}} class="btn btn-danger">Cancel</button>
        </div>
    </div>
</div>

// app/controller/cart.js
import Controller from '@ember/controller';

const { service } = Ember.inject;

export default Controller.extend({
    session: service('session'),
    currentUser: service('currentUser'),
    shoppingCart: service('shopping-cart'),
});
class ProductsController < ApplicationController
    def index
        if params[:id]
            render json: Product.find(params[:id]) 
        else
            render json: Product.all 
        end
        
    end

    def show
        render json: Product.find(params[:id])
    end
    def create
        title = params[:product][:title]
        description = params[:product][:description]
        price = params[:product][:price]
        quantity = params[:product][:quantity]

        Product.create!(
            title: title,
            description: description,
            price: price,
            quantity: quantity,
        )

    end

    def update
    end
end

【问题讨论】:

  • 您能否提供有关您正在使用的 API 调用、响应和 DOM 结构的更多详细信息?
  • 是的,我会提供的
  • 我投票结束这个问题,因为如何实现一个完整的功能不是一个范围合理的实用编程问题,可以在几段中回答。这需要一个冗长的教程或一本书作为答案。

标签: ruby-on-rails ruby ember.js


猜你喜欢
  • 2011-12-19
  • 2017-05-31
  • 2023-03-30
  • 1970-01-01
  • 2022-11-24
  • 1970-01-01
  • 2020-12-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多