Magento 2 error in swatchRenderer.js



我已经覆盖了 magento SwatchRenderer.js appcodeMydirectoryCustomSwatchesviewfrontendwebjsSwatchRenderer.js 中的文件。

我的问题是我的产品页面加载出错:

捕获的类型错误:无法读取未定义的属性"updateData"

我发现SwatchRenderer.js的以下函数上的data('gallery')是未定义的。

updateBaseImage: function (images, context, isProductViewExist) {
        var justAnImage = images[0];
        if (isProductViewExist) {
            context
                .find('[data-gallery-role=gallery-placeholder]')
                .data('gallery')
                .updateData(images);
        } else if (justAnImage && justAnImage.img) {
            context.find('.product-image-photo').attr('src', justAnImage.img);
        }
    }

我检查了一个Magento 2演示网站。在该站点上,上述数据属性被设置为JavaScript对象。目标元素是具有上述属性的div。但是在我的网站上它是未定义的,显然我认为我的网站上没有设置数据属性。谁能帮我找到上述元素的setter函数/视图/文件?任何帮助将不胜感激。谢谢。

您的Magento实例中使用了什么主题?是否重命名了容器类名称?

在 SwatchRenderer.js 文件的第 202 行可以找到一段有趣的代码。在 _create 函数下,您将找到图库变量的初始化,如下所示

您会注意到,它在 .column.main 元素下找到带有数据库的元素。因此,由于缺少列主元素将返回空响应。

我找到了一种非常有效的方法来解决这个问题:

/vendor/magento/module-swatches/view/frontend/web/js/swatch-renderer.js -file 复制到app/design/YourName/YourTheme/Magento_Swatches/web/js/swatch-renderer.js,并将 updateBaseImage() 中的代码(第 ~1152 行)替换为以下内容:

updateBaseImage: function (images, context, isInProductView, eventName) {
    var gallery = context.find(this.options.mediaGallerySelector).data('gallery');
    if (eventName === undefined && gallery !== undefined) {
        this.processUpdateBaseImage(images, context, isInProductView, gallery);
    } else {
        context.find(this.options.mediaGallerySelector).on('gallery:loaded', function (loadedGallery) {
            loadedGallery = context.find(this.options.mediaGallerySelector).data('gallery');
            this.processUpdateBaseImage(images, context, isInProductView, loadedGallery);
        }.bind(this));
    }
},

诀窍是:此方法不会等待图库完全加载,而此事件(gallery:loaded)是现成的。通过将其添加到方法中,它可以正常工作。

我只是希望Magento Dev能够接受这一点并在核心代码中实现这一点。

最新更新