首页 > 解决方案 > 如何通过 mixin 将新的 JS 函数添加到 Magento 结帐付款页面的运输信息部分?

问题描述

我正在尝试在 Magento 2 中为结帐/付款页面运输信息部分添加一个 mixin。

现有部分vendor/magento/module-checkout/view/frontend/web/template/shipping-information/address-renderer/default.html如下:

<each args="data: address().customAttributes, as: 'element'">
   <text args="$parent.getCustomAttributeLabel(element)"/>
   <br/>
</each>

我想创建一个 myNewFunction() 并从这里调用它。所以,我暂时添加if="$parent.myNewFunction(element)"了它,如下所示:

<each args="data: address().customAttributes, as: 'element'">
   <text if="$parent.myNewFunction(element)" args="$parent.getCustomAttributeLabel(element)"/>
   <br/>
</each>

该预先存在的功能getCustomAttributeLabel在 中定义vendor/magento/module-checkout/view/frontend/web/js/view/shipping-information/address-renderer/default.js

这是我需要添加我myNewFunction()的地方。我不想覆盖整个文件并将其复制到我的主题中,所以我试图通过 mixin 将函数添加到它。

为此,我已经删除了一个模块:app/code/MyCompany.

在这个模块中,我创建了:

app/code/MyCompany/Checkout/view/frontend/requirejs-config.js

使用此代码:

var config = {
    config: {
        mixins: {
            'Magento_Checkout/js/view/shipping-information/address-renderer/default': {
                'MyCompany_Checkout/js/view/shipping-information/address-renderer/default-mixin': true
            }
        }
    }
};

然后我在以下位置创建了 mixin 本身:

app/code/MyCompany/Checkout/view/frontend/web/js/view/shipping-information/address-renderer/default-mixin.js

使用此代码:

define([
    'uiComponent',
    'underscore',
    'Magento_Customer/js/customer-data'
], function (Component, _, customerData) {
    'use strict';

    return function (target) {
        return target.extend({
            myNewFunction: function (element) {
                console.log(element);
                return false;
            }
        });
    }
});

我目前在 Magento 中将部署模式设置为“开发”。尽管如此,我还是尝试删除所有 var/* 文件,再次生成静态内容,并清除缓存,以取得良好的效果。

无论如何,在加载结帐/付款页面时,我一直在控制台中收到此 JS 错误:

$parent.myNewFunction is not a function

我在这里做错了什么?

我怀疑模块需要有一个 register.php?或者模块没有加载?然而,我已经看到了很多其他的例子,比如这个指南,这个 Magento mixin stackoverflow question,以及这个关于如何通过 mixin 添加 shipping.js 功能的例子,requirejs-config.js除了声明和之外,没有提到对模块做更多的事情mixin JS 文件本身。

标签: magento2mixins

解决方案


刚刚找到了一种使用“mixins”覆盖该功能的方法。在 requirejs-config.js 文件中,我必须添加:

config: {
            mixins: {
                'Magento_Checkout/js/view/shipping': {
                    'Mynamespace_Mymodule/js/view/shipping': true
                }
            }
        }

推荐阅读