如何将“空购物车”按钮添加到小型购物车


Answers:


15

我刚刚为您的问题创建了一个合适的模块:

我们需要声明自定义js组件和html模板:

应用/代码/供应商/ MiniCart /视图/前端/布局/default.xml

<?xml version="1.0"?>

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="minicart">
            <arguments>
                <argument name="jsLayout" xsi:type="array">
                    <item name="types" xsi:type="array"/>
                    <item name="components" xsi:type="array">
                        <item name="minicart_content" xsi:type="array">
                            <item name="component" xsi:type="string">Vendor_MiniCart/js/view/minicart</item>
                            <item name="config" xsi:type="array">
                                <item name="template" xsi:type="string">Vendor_MiniCart/minicart/content</item>
                            </item>
                        </item>
                    </item>
                </argument>
            </arguments>
        </referenceBlock>
    </body>
</page>

应用/代码/供应商/MiniCart/view/frontend/web/js/view/minicart.js

   define([
    'jquery',
    'Magento_Checkout/js/view/minicart',
    'Magento_Ui/js/modal/alert',
    'Magento_Ui/js/modal/confirm'
], function ($ ,Component, alert, confirm) {
    'use strict';

    return Component.extend({
        confirmMessage: $.mage.__('Are you sure you would like to remove all items from the shopping cart?'),
        emptyCartUrl: window.checkout.emptyMiniCart,

        emptyCartAction: function (element) {
            var self = this,
                href = self.emptyCartUrl;
            $(element).on('click', function () {
                var el = this;
                confirm({
                    content: self.confirmMessage,
                    actions: {
                        confirm: function () {
                            self._removeAllItems(href, el);
                        },
                        always: function (event) {
                            event.stopImmediatePropagation();
                        }
                    }
                });
            });
        },

        _removeAllItems: function (href, elem) {
            $.ajax({
                url: href,
                type: 'post',
                dataType: 'json',
                beforeSend: function () {
                    $(elem).attr('disabled', 'disabled');
                },
                complete: function () {
                    $(elem).attr('disabled', null);
                }

            }).done(function (response) {
                if (!response.errors) {

                } else {
                    var msg = response.message;

                    if (msg) {
                        alert({
                            content: msg
                        });
                    }
                }
            }).fail(function (error) {
                console.log(JSON.stringify(error));
            });
        }
    });
});

emptyCartUrl: window.checkout.emptyMiniCart,我们将从checkout config:中获得空链接app/code/Vendor/MiniCart/Plugin/Cart/ConfigPlugin.php(稍后声明)。

我们需要从原始文件中复制微型购物车的内容:vendor/magento/module-checkout/view/frontend/web/template/minicart/content.html。然后,在我们的自定义文件中,我们需要添加操作文本:

app / code / Vendor / MiniCart / view / frontend / web / template / minicart / content.html

 <!-- ko if: getCartParam('summary_count') -->
    <div class="actions">
        <div class="secondary">
            <a class="action empty-cart" id="empty-minicart" data-bind="afterRender: emptyCartAction">
                <span><!-- ko i18n: 'Empty Cart Now' --><!-- /ko --></span>
            </a>
        </div>
    </div>
 <!-- /ko -->

声明DI以将空链接添加到结帐配置:

应用/代码/供应商/MiniCart/etc/frontend/di.xml

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Checkout\Block\Cart\Sidebar">
        <plugin name="empty_cart_url" type="Vendor\MiniCart\Plugin\Cart\ConfigPlugin" sortOrder="20" />
    </type>
</config>

应用程序/代码/供应商/MiniCart/Plugin/Cart/ConfigPlugin.php

<?php

namespace Vendor\MiniCart\Plugin\Cart;

use Magento\Framework\UrlInterface;

class ConfigPlugin
{
    /**
     * @var UrlInterface
     */
    protected $url;

    /**
     * ConfigPlugin constructor.
     * @param UrlInterface $url
     */
    public function __construct(
        UrlInterface $url
    ) {
        $this->url = $url;
    }

    /**
     * @param \Magento\Checkout\Block\Cart\Sidebar $subject
     * @param array $result
     * @return array
     */
    public function afterGetConfig(
        \Magento\Checkout\Block\Cart\Sidebar $subject,
        array $result
    ) {
        $result['emptyMiniCart'] = $this->url->getUrl('minicart/cart/emptycart');
        return $result;
    }
}

现在,我们需要构建控制器:

应用程序/代码/供应商/MiniCart/etc/frontend/routes.xml

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="standard">
        <route id="minicart" frontName="minicart">
            <module name="Vendor_MiniCart" />
        </route>
    </router>
</config>

应用程序/代码/供应商/MiniCart/Controller/Cart/EmptyCart.php

<?php

namespace Vendor\MiniCart\Controller\Cart;

use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\Json\Helper\Data;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Checkout\Model\Session;
use Psr\Log\LoggerInterface;

class EmptyCart extends Action
{
    /**
     * @var Session
     */
    protected $checkoutSession;

    /**
     * @var JsonFactory
     */
    protected $jsonFactory;

    /**
     * @var Data
     */
    protected $jsonHelper;

    /**
     * @var LoggerInterface
     */
    protected $logger;

    /**
     * @var Magento\Checkout\Model\Cart
     */
    protected $cart;

    /**
     * EmptyCart constructor.
     *
     * @param Context $context
     * @param Session $session
     * @param JsonFactory $jsonFactory
     * @param Data $jsonHelper
     * @param LoggerInterface $logger
     */
    public function __construct(
        Context $context,
        Session $session,
        JsonFactory $jsonFactory,
        Data $jsonHelper,
        LoggerInterface $logger,
        \Magento\Checkout\Model\Cart $cart
    ) {
        $this->checkoutSession = $session;
        $this->jsonFactory = $jsonFactory;
        $this->jsonHelper = $jsonHelper;
        $this->logger = $logger;
        $this->cart = $cart;
        parent::__construct($context);
    }

    /**
     * Ajax execute
     *
     */
    public function execute()
    {
        $response = [
            'errors' => false
        ];

        if ($this->getRequest()->isAjax()) {
            try {
                $this->cart->truncate()->save();
                $response['message'] = __('Empty Cart.');

            } catch (\Exception $e) {
                $response = [
                    'errors' => true,
                    'message' => __('Some thing went wrong.')
                ];
                $this->logger->critical($e);
            }
        } else {
            $response = [
                'errors' => true,
                'message' => __('Need to access via Ajax.')
            ];
        }
        /** @var \Magento\Framework\Controller\Result\Raw $resultRaw */
        $resultJson = $this->jsonFactory->create();
        return $resultJson->setData($response);
    }
}

需要重新加载购物车部分:

app / code / Vendor / MiniCart / etc / frontend / sections.xml

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Customer:etc/sections.xsd">
    <action name="minicart/cart/empty">
        <section name="cart"/>
    </action>
</config>

记住创建registration.phpmodule.xml

应用/代码/供应商/MiniCart/registration.php

<?php

\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Vendor_MiniCart',
    __DIR__
);

app / code / Vendor / MiniCart / etc / module.xml

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Vendor_MiniCart" setup_version="1.0.0"/>
</config>

[影像演示]

迷你购物车:

在此处输入图片说明

消息确认:

在此处输入图片说明


感谢您提供如此详尽而完整的解决方案!它起作用了,除了清空购物车的代码。要使其在2.1.10上运行,我必须对其进行一些更改pastebin.com/sYmhqYRL
Viperet

2
甚至更短的pastebin.com/2tMEMdeA
Viperet

1
@Viperet我同意你的看法。应该使用$this->cart->truncate()->save();。随时编辑我的答案。
Khoa TruongDinh

实施上述代码后,@ KhoaTruongDinh迷你购物车仅显示“立即清空购物车”按钮。有什么办法吗?
维沙尔18'Jan

1
我的Magento版本是2.2.6。你能帮我么?
Rohan Hapani
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.