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;
}
相關文章
相關標籤/搜索