magento2 checkout javascript剖析

checkout是一个独立的组件,整个checkout步骤先从数据开始,经过LayoutProcessor合成全部附加在checkout上的数据,并把数据转为JSON格式的jsLayout数据,最后数据由众多JS组件把页面呈现出来。javascript

LayoutProcessor以前的数据是由多个layout.xml提供的,若是要给checkout附加更多数据,最标准的作法是layout.xml里追加。但xml格式描述能力有限,可能会须要用更粗暴的方法,即用DI修改Magento\Checkout\Block\Checkout\LayoutProcessor。checkout data是个十分巨大的数据,要想修改先要想办法把原始数据展现出来,我用的方法以下:
vendor/magento/module-checkout/view/frontend/templates/onepage.phtmlphp

<?php
$jsLayout = $block->getJsLayout();
?>
<?php if(isset($_GET['debug']) && $_GET['debug']=='checkout'):?>
<?php
    // krumo能够更优雅地展现Array,须要自行添加
    \krumo::dump(\Zend_Json::decode($jsLayout)['components']['checkout']['children']);
?>
<?php else:?>
    <!-- 原页面内容 -->
<?php endif;?>

checkout 默认有两页流程,shipping和payment。整个checkout由众多JS组件组成,有两个页面入口组件,要修改JS组件最好先从两个入口组件入手。html

vendor/magento/module-checkout/view/frontend/web/template/payment.html
vendor/magento/module-checkout/view/frontend/web/js/view/payment.js
vendor/magento/module-checkout/view/frontend/web/template/shipping.html
vendor/magento/module-checkout/view/frontend/web/js/view/shipping.js

从shpping切换到payment页须要 Magento_Checkout/js/model/step-navigator 进行跳转。
checkout里所用的到数据依赖于 Magento_Checkout/js/model/quote前端

checkout前端经常使用数据

当前选中的送货方式java

quote.shippingMethod().method_code
quote.shippingMethod().carrier_code

当前选中的送货地址web

quote.shippingAddress()

当前选中的账单地址frontend

quote.billingAddress()

当前选中的支付方式函数

quote.paymentMethod()

billingAddress如何与payment拆开?

默认状况下billingAddress被包含在payment的模板里面,而payment通常是一个module,每一个payment模板都会输出billingAddress。不过这种设计并不合理,通常payment与billingAddress分两块状况会比较清晰。this

vendor/magento/module-checkout/view/frontend/web/js/view/payment/list.js
追加 Magento_Checkout/js/model/quote来提取quote数据并插入如下函数debug

getBillingAddressRegionName: function(){
    if(quote.paymentMethod())
        return 'billing-address-form-'+quote.paymentMethod().method;
    else
        return 'billing-address-form-checkmo';
}

vendor/magento/module-checkout/view/frontend/web/template/payment-methods/list.html

<div class="payment-method-billing-address">
    <div class="step-title" data-role="title" data-bind="i18n:'Billing Address'"></div>
    <!-- ko foreach: getRegion(getBillingAddressRegionName()) -->
    <!-- ko template: getTemplate() --><!-- /ko -->
    <!--/ko-->
</div>

而后用CSS把payment里的billingAddress部分隐藏

在checkout的元素中加placeholder

使用plugin修改LayoutProcessor

protected function _processShippingAddressFrom( & $fieldset )
{
    $fieldset['street']['children'][0]['placeholder'] = __('Enter your address');
}

public function afterProcess( \Magento\Checkout\Block\Checkout\LayoutProcessor $layoutProcessor, array $jsLayout )
{
    $this->_processShippingAddressFrom( $jsLayout['components']['checkout']['children']['steps']['children']
            ['shipping-step']['children']['shippingAddress']['children']['shipping-address-fieldset']['children'] );

    return $jsLayout;
}
相关文章
相关标签/搜索