magento2 - 如何通过 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 文件本身。
解决方案
刚刚找到了一种使用“mixins”覆盖该功能的方法。在 requirejs-config.js 文件中,我必须添加:
config: {
mixins: {
'Magento_Checkout/js/view/shipping': {
'Mynamespace_Mymodule/js/view/shipping': true
}
}
}
推荐阅读
- asp.net - 使用 Angular 9 在 Asp.Net Core Web API 中发布数据(发布请求)时出错
- javascript - 阅读更多
- iframe - Microsoft Graph - 在 iFrame 中嵌入在线会议
- sql - 在SQL上的一行中合并具有相同ID的多行描述
- python-3.x - Python:无法使用 subprocess.run 启动 JSON 服务器
- ios - Swift 将音乐库导入我的 iOS 应用程序,并为 iTunes 音乐、苹果音乐提供不同的 tableview 单元格
- android - java.lang.IllegalStateException:迁移没有正确处理。表未更改
- reactjs - 显示列表的另一个资源
- regex - 匹配以 TE 开头且正好有 11 个字符的单词
- python - 读取 rtsp 时出现 Ubuntu OpenCV 错误