问题描述
我正在尝试在 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
}
}
}
};
然后我在:
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 吗?或者模块没有加载?然而,我已经看到了很多其他示例,例如 this guide、这个 Magento mixin stackoverflow question 和 this example on how to add shipping.js functionality via mixin,除了声明 {{1}和 mixin JS 文件本身。
解决方法
刚刚找到了一种使用“mixins”覆盖该函数的方法。 在 requirejs-config.js 文件中,我必须添加:
config: {
mixins: {
'Magento_Checkout/js/view/shipping': {
'Mynamespace_Mymodule/js/view/shipping': true
}
}
}